how to refresh my custom listview - android

I'm updating the database to other classes and I want the custom listview to be updated when I get to the main activity. My customListview is still standing
I have searched for this problem, but I could not solve it myself. Where should I add the code to solve this problem? Please help me 3 days did not solve my problem.
public class MainActivity extends AppCompatActivity {
veritabani vtabani; //database
List<Yukleclas> yuklele =new ArrayList<Yukleclas>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vtabani=new veritabani(this);
OzelAdaptor adaptor=new OzelAdaptor(this,yuklele);
ListView listView=(ListView) findViewById(R.id.listview);
String[] sutunlar =
{"id","bilgi","simdikiyil","simdikiay","simdikigun","alarmsaat",
"alarmdakika","gsonrayil","gsonraay","gsonragun","hsonrayil","hsonraay",
"hsonragun","asonrayil","asonraay","asonragun","seviye","durum"};
SQLiteDatabase dboku =vtabani.getReadableDatabase();
Cursorcursor=dboku.query("tablo_adi",sutunlar,null,null,null,null,null);
while (cursor.moveToNext()) {
if (cursor.getInt(17)==1) {
yuklele.add(new Yukleclas(cursor.getString(1), cursor.getInt(2),
cursor.getInt(3), cursor.getInt(4),
cursor.getInt(7),cursor.getInt(8),cursor.getInt(9),cursor.getInt(10),
cursor.getInt(11),cursor.getInt(12),cursor.getInt(13),cursor.getInt(14),
cursor.getInt(15),cursor.getInt(16)));
}
}
cursor.close();
dboku.close();
listView.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
}
public void ekleyegit(View view) {
Intent intent =new Intent(this,ekleactivity.class);
startActivity(intent);
finish();
}}
and this is myAdapter:
public class OzelAdaptor extends BaseAdapter {
LayoutInflater layoutInflater;
List<Yukleclas> list;
public OzelAdaptor(Activity activity,List<Yukleclas> mList){
layoutInflater= (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
list=mList;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View satirView;
satirView=layoutInflater.inflate(R.layout.satir,null);
TextView tv_tarih = (TextView) satirView.findViewById(R.id.text_tarih);
TextView tv_bilgi= (TextView) satirView.findViewById(R.id.text_bilgi);
ImageView imageView= (ImageView) satirView.findViewById(R.id.imageView);
Yukleclas yukleclas =list.get(position);
tv_bilgi.setText(yukleclas.getBilgi());
if(yukleclas.getSeviye()==1){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getGun() +"/" +yukleclas.getAy() + "/" +yukleclas.getYil() );
}else if(yukleclas.getSeviye()==2){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getGsgun() +"/" +yukleclas.getGsay() + "/" +yukleclas.getGsyil() );
}else if (yukleclas.getSeviye()==3){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getHsgun() +"/" +yukleclas.getHsay() + "/" +yukleclas.getHsyil() );
}else if (yukleclas.getSeviye()==4){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getAsgun() +"/" +yukleclas.getAsay() + "/" +yukleclas.getAsyil() );
}
if(yukleclas.getSeviye()==1){
imageView.setImageResource(bir); // eğer 1. seviyede ise bir isimli ikonu göster
}else if(yukleclas.getSeviye()==2){
imageView.setImageResource(iki);
}else if(yukleclas.getSeviye()==3){
imageView.setImageResource(uc);
}else if(yukleclas.getSeviye()==4){
imageView.setImageResource(ic_launcher);
}
return satirView;
}
}
and this is my class to get-set:
public class Yukleclas {
private String bilgi;
private int yil;
private int ay;
private int gun;
private int seviye;
private int gsyil;
private int gsay;
private int gsgun;
private int hsyil;
private int hsay;
private int hsgun;
private int asyil;
private int asay;
private int asgun;
public Yukleclas(String mBilgi,int mYil,int mAy,int mGun,int mGsyil,int
mGsay,int mGsgun,int mHsyil,int mHsay,int mHsgun,int mAsyil,int mAsay,int
mAsgun,int mSeviye){
yil=mYil;
bilgi=mBilgi;
ay=mAy;
gun=mGun;
gsyil=mGsyil;
gsay=mGsay;
gsgun=mGsgun;
hsyil=mHsyil;
hsay=mHsay;
hsgun=mHsgun;
asyil=mAsyil;
asay=mAsay;
asgun=mAsgun;
seviye=mSeviye;
}
public int getYil() {
return yil;
}
public void setYil(int yil) {
this.yil = yil;
}
public int getSeviye() {
return seviye;
}
public void setSeviye(int yil) {
this.seviye = seviye;
}
public String getBilgi() {
return bilgi;
}
public void setBilgi(String bilgi) {
this.bilgi = bilgi;
}
public int getAy() {
return ay;
}
public void setAy(int ay) {
this.ay = ay;
}
public int getGun() {
return gun;
}
public void setGun(int gun) {
this.gun = gun;
}
public int getGsyil() {return gsyil;
}
public void setGsyil(int gsyil) {this.gsyil = gsyil;
}
public int getGsay() {return gsay;
}
public void setGsay(int gsay) {this.gsay = gsay;
}
public int getGsgun() {return gsgun;
}
public void setGsgun(int gsgun) {this.gsgun = gsgun;
}
public int getHsyil() {return hsyil;
}
public void setHsyil(int hsyil) {this.hsyil = hsyil;
}
public int getHsay() {return hsay;
}
public void setHsay(int hsay) {this.hsay = hsay;
}
public int getHsgun() {return hsgun;
}
public void setHsgun(int hsgun) {this.hsgun = hsgun;
}
public int getAsyil() {return asyil;
}
public void setAsyil(int asyil) {this.asyil = asyil;
}
public int getAsay() {return asay;
}
public void setAsay(int asay) {this.asay = asay;
}
public int getAsgun() {return asgun;
}
public void setAsgun(int asgun) {this.asgun = asgun;
}
}
I know it is very complex but How to replace my customlistview ?

Easy way is to call adapter.notifyDataSetChanged() in your onResume function.
But I would suggest you check if your list has been updated then only you call adapter.notifyDataSetChanged(). You can do this in multiple ways, but for a cleaner approach use EventBus which allows you to fire events and listen to them, So you can fire an event every time you update your dataBaseand on listening to this event, simply call adapter.notifyDataSetChanged

Related

While searching using EditText, the items in Recyclerview is duplicating, if i am searching fast

In my project, there is need of searching data from server using keyword. After search, i am displaying results using RecyclerView . While searching fast, the data in RecyclerView is duplicating. If searching slowly, it's working fine. Any suggestions are appreciated. Thank you.
The below code for making server call:
private void callSearchUserApi(final String searchText, int currentPage, boolean clearData) {
isApiCallInProcess = true;
String URL = "userinfo/api/v1/user-search/" + "?page=" + currentPage;
if (!Connectivity.isConnected(activity)) {
Common.snackBarNoConnection(activity, activity.getString(R.string.no_conection));
//setOnProgressbarVisibility(View.GONE);
return;
}
if (clearData) {
globalSearchUsersModelList.clear();
//BS globalSearchUserResultsAdapter.notifyDataSetChanged();
}
ApiInterface apiCall = ApiClient.getApiService(activity);
final Call<SearchUsersModel> globalUserSearchApiCall = apiCall.searchUser(
URL,
searchText);
globalUserSearchApiCall.enqueue(new Callback<SearchUsersModel>() {
#Override
public void onResponse(Call<SearchUsersModel> call, Response<SearchUsersModel> response) {
if (response.isSuccessful() && response.body().getStatus().equalsIgnoreCase(Common.SUCCESS_RESPONSE)) {
//BS globalSearchUsersModelList.addAll(response.body().getData().getData());
for (int i = 0; i < response.body().getData().getData().size(); i++) {
SearchUsersModel.DataBeanX.DataBean dataBean = new SearchUsersModel.DataBeanX.DataBean();
dataBean.setDesignation(response.body().getData().getData().get(i).getDesignation());
dataBean.setFull_name(response.body().getData().getData().get(i).getFull_name());
dataBean.setGender(response.body().getData().getData().get(i).getGender());
dataBean.setId(response.body().getData().getData().get(i).getId());
dataBean.setPlace(response.body().getData().getData().get(i).getPlace());
dataBean.setProfile_pic(response.body().getData().getData().get(i).getProfile_pic());
globalSearchUsersModelList.add(dataBean);
/*BS if (!globalSearchUsersModelList.contains(response.body().getData().getData().get(i)))
globalSearchUsersModelList.add(response.body().getData().getData().get(i));*/
}
CURRENT_PAGE = response.body().getData().getPage();
isLoading = false;
if (response.body().getData().isNext() == false)
isLastPage = true;
else
isLastPage = false;
if (globalSearchUsersModelList.size() == 0) {
rv_GlobalsearchList.setVisibility(View.GONE);
rl_placeholderGSPeople.setVisibility(View.VISIBLE);
tv_placeholderGSPeople.setText(activity.getString(R.string.no_search_found) + " " + searchText);
} else {
rv_GlobalsearchList.setVisibility(View.VISIBLE);
rl_placeholderGSPeople.setVisibility(View.GONE);
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
globalSearchUserResultsAdapter.notifyDataSetChanged();
}
});
}
if (searchTextsList.size() > 0) {
String sText = searchTextsList.get(0);
searchTextsList.remove(0);
callSearchUserApi(sText, FIRST_PAGE, true);
} else
isApiCallInProcess = false;
}
#Override
public void onFailure(Call<SearchUsersModel> call, Throwable t) {
isApiCallInProcess = false;
}
});
}
This is my Adapter.
public class GlobalSearchUserResultsAdapter extends RecyclerView.Adapter<GlobalSearchUserResultsAdapter.SearchViewHolder> {
private Context context;
private List<SearchUsersModel.DataBeanX.DataBean> searchUserList;
public GlobalSearchUserResultsAdapter(Context context, List<SearchUsersModel.DataBeanX.DataBean> searchUserList){
this.context = context;
this.searchUserList = searchUserList;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.v("Search", "Adapter Activity : "+context);
View view = LayoutInflater.from(context).inflate(R.layout.global_search_row, parent, false);
return new GlobalSearchUserResultsAdapter.SearchViewHolder(view);
}
#Override
public void onBindViewHolder(GlobalSearchUserResultsAdapter.SearchViewHolder holder, int position) {
if ( searchUserList.get(position).getGender().equals("M")) {
holder.iv_userImage.setBackgroundResource(R.drawable.white_border_with_circle_appblue);
Common.setGlideImage((GlobalSearchActivity)context,
holder.iv_userImage,
/*searchUsersModel*/searchUserList.get(position).getProfile_pic(),
R.drawable.male,
true);
} else if (searchUserList.get(position).getGender().equals("F")) {
holder.iv_userImage.setBackgroundResource(R.drawable.white_border_with_circle_pink);
Common.setGlideImage((GlobalSearchActivity)context,
holder.iv_userImage,
searchUserList.get(position).getProfile_pic(),
R.drawable.female,
true);
} else {
Common.setGlideImage((GlobalSearchActivity)context,
holder.iv_userImage,
searchUserList.get(position).getProfile_pic(),
R.drawable.deafult_profilepic,
true);
}
holder.tv_userName.setText(searchUserList.get(position).getFull_name());
holder.tv_userName.setTypeface(Common
.getFontTypeface(context, GlobalConstants.FONT_AVENIR_MEDIUM));
holder.tv_place.setText(searchUserList.get(position).getPlace());
holder.tv_place.setTypeface(Common
.getFontTypeface(context, GlobalConstants.FONT_AVENIR_MEDIUM));
holder.designation.setText(searchUserList.get(position).getDesignation());
}
#Override
public int getItemCount() {
return searchUserList.size();
}
public class SearchViewHolder extends RecyclerView.ViewHolder{
private ImageView iv_userImage;
private TextView tv_userName;
private TextView tv_place;
private TextView designation;
public SearchViewHolder(View itemView) {
super(itemView);
this.iv_userImage = (ImageView) itemView.findViewById(R.id.imageSearch);
this.tv_userName = (TextView) itemView.findViewById(R.id.nameSearch);
tv_userName.setTypeface(Common.getFontTypeface(context,
GlobalConstants.FONT_AVENIR_MEDIUM));
this.designation = (TextView) itemView.findViewById(R.id.designation);
designation.setTypeface(Common.getFontTypeface(context,
GlobalConstants.FONT_AVENIR_MEDIUM));
this.tv_place = (TextView) itemView.findViewById(R.id.placeSearch);
tv_place.setTypeface(Common.getFontTypeface(context,
GlobalConstants.FONT_AVENIR_LIGHT));
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.startActivity(new Intent(context, ProfileActivity.class)//ThirdParty
.putExtra(GlobalConstants.KEY_THIRD_PARTY_ID, searchUserList.get(getAdapterPosition()).getId()));
}
});
}
}
}
You just had to clear the globalSearchUsersModelList list just before for loop, because API call is asynchronous.
globalSearchUsersModelList.clear();// Important one
for (int i = 0; i < response.body().getData().getData().size(); i++) {
// do your stuff
}
I think the issue come from your getItemId implementation. The way you implement it, the recycler view will identify an item according to its position in the list.
If you change this and use unique identification for instance searchUserList.get(position).id (if your User object has an unique ID) the problem should be fixed
You can also add in your activity adapter.setHasStableIds(true)

Add data to Arraylist Object from fragment

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

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.

One ListView Receiving Data from Multiple Class

I am looking for something like this:
several <ItemTemplate> in one ListView.
But it was in .ASP and above my level.
What I need
Class Vitals: vTime, BP, Heart Rate, Respirations per Minute, etc.
Class Medications: mTime, RxName, RxRoute, RxDose, RxDoseUnit, etc.
Class Procedures: pTime, Intubation, IV insertion, Defibrillation, etc.
Classes Vitals, Medications and Procedures to be based on user input that inject in to a ListView (sorted chronologically). A "Many-to-One" if I may.
I've went through hours of "CustomAdapter & ListView" tutorials, code samples, walkthroughs.
Here is my current code (trashed and scattered) to show that I am actively working towards a solution:
/*
* Created by SwaLayS on 2/19/2015.
*/
public class VitalAdapter extends BaseAdapter {
private ArrayList<VitalItem> vitalData;
private LayoutInflater layoutInflater;
public VitalAdapter(Context acontext, ArrayList<VitalItem> vitalData){
this.vitalData=vitalData;
layoutInflater=LayoutInflater.from(acontext);
}
#Override
public int getCount() {
return vitalData.size();
}
#Override
public Object getItem(int position) {
return vitalData.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.inflate(R.layout.vital_view_children,null);
holder = new ViewHolder();
}
}
public class VitalView extends RelativeLayout {
private TextView vTimeTV;
// private TextView vPTATV;
private TextView vRateTV;
private TextView vOxySatTV;
private TextView vSysBPTV;
private TextView vDiaBPTV;
private TextView vRespRateTV;
private TextView vRespEffortTV;
//private TextView vMethodBPTV;
public static VitalView inflate(ViewGroup parent){
VitalView vitalView = (VitalView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.vital_view,parent,false);
return vitalView;
}
public VitalView(Context c){
this(c,null);
}
public VitalView(Context context, AttributeSet attrs){
this(context, attrs,0);
}
public VitalView(Context context, AttributeSet attrs, int defStyle){
super(context,attrs,defStyle);
LayoutInflater.from(context).inflate(R.layout.vital_view_children, this,true);
setupChildren();
}
private void setupChildren(){
vTimeTV = (TextView)findViewById(R.id.vTime);
// vPTATV = (TextView)findViewById(R.id.vPTA);
vRateTV = (TextView) findViewById(R.id.vBPM);
vOxySatTV = (TextView) findViewById(R.id.vOsat);
vSysBPTV = (TextView) findViewById(R.id.vSystolic);
vDiaBPTV = (TextView)findViewById(R.id.vDiastolic);
vRespRateTV = (TextView) findViewById(R.id.vRespRate);
vRespEffortTV = (TextView)findViewById(R.id.vRespEffort);
// vMethodBPTV = (TextView)findViewById(R.id.vMethodBP
}
public void setVital(VitalItem vital){
//vTimeTV.setText(vital.get);
}
}
public class VitalItem {
private String vTime;
// private String vPTA;
private String vRate;
private String vOxySat;
private String vSysBP;
private String vDiaBP;
private String vRespRate;
private String vRespEffort;
// private String vMethodBP;
public VitalItem(String Time, String Rate, String OxySat, String SysBP, String DiaBp, RespRate, String RespEffort){
super();
vTime=Time;
// vPTA=PTA;
vRate=Rate;
vOxySat = OxySat;
vSysBP = SysBP;
vDiaBP = DiaBP;
vRespRate = RespRate;
vRespEffort=RespEffort;
//vMethodBP=MethodBP;
}
public String getvTime() {
return vTime;
}
public void setvTime(String vTime) {
this.vTime = vTime;
}
// public String getvPTA() {
// return vPTA;
// }
// public void setvPTA(String vPTA) {
// this.vPTA = vPTA;
// }
public String getvRate() {
return vRate;
}
public void setvRate(String vRate) {
this.vRate = vRate;
}
public String getvOxySat() {
return vOxySat;
}
public void setvOxySat(String vOxySat) {
this.vOxySat = vOxySat;
}
public String getvSysBP() {
return vSysBP;
}
public void setvSysBP(String vSysBP) {
this.vSysBP = vSysBP;
}
public String getvDiaBP() {
return vDiaBP;
}
public void setvDiaBP(String vDiaBP) {
this.vDiaBP = vDiaBP;
}
public String getvRespRate() {
return vRespRate;
}
public void setvRespRate(String vRespRate) {
this.vRespRate = vRespRate;
}
public String getvRespEffort() {
return vRespEffort;
}
public void setvRespEffort(String vRespEffort) {
this.vRespEffort = vRespEffort;
}
// public String getvMethodBP() {
// return vMethodBP;
//}
// public void setvMethodBP(String vMethodBP) {
// this.vMethodBP = vMethodBP;
//
}
}
I'd appreciate any and everything;
I'm working on a NEMSIS . org project;
I may even be searching with the wrong search terms for what I need.
All help is appreciated
have you try the getViewTypeCount() method in adapter,
it can define different itemView for your different data types.
for your case you need to define three layout items .
search some demos,it may help you .

I want to pass hashmap from custom arrayadapter to activity?

I want to pass HashMap or ArrayList Object from Custom ArrayAdapter to activity which fills the ListView.I want to send checked records recordId field.I m new To Android.Any Suggestion Plz
Pass the adapter a reference to the activity. Then provide a method in the activity that the adapter can call.
In adapter:
private MyActivity activity;
public void setActivity(MyActivity activity) {
this.activity = activity;
}
In Activity:
// create adapter
adapter.setActvity(this);
In adapter (when you want to pass parameters back to activity):
activity.setHashMap(mymap);
My CustomAdapter Class::
class SearchResultAdapter extends ArrayAdapter{
Context context;
int layoutResourceId;
private ArrayList<SearchResultModel> results;
public SearchResultAdapter(Context context, int layoutResourceId, ArrayList<SearchResultModel> results) {
super(context, layoutResourceId, results);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.results = results;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
SearchResultHolder holder=null;
if(row == null)
{
LayoutInflater vi = ((Activity)context).getLayoutInflater();
row = vi.inflate(R.layout.listitemrow, null);
holder = new SearchResultHolder();
holder.jobdetails = (TextView)row.findViewById(R.id.jobdetails);
row.setTag(holder);
}
else
{
holder = (SearchResultHolder)row.getTag();
}
SearchResultModel model = results.get(position);
if (model != null)
{
row.setId(Integer.parseInt(model.getjob_id()));
String result=
"<font color=#5D2E8C>"+model.getjob_title()+"</font><br>" +
"<font color=#737373>"+model.getpost_date()+"</font><br>"+model.getuser_name()+"<br>" +
"<font color=#3C5A98>"+model.getsalary()+" Rs (Per Annum)</font><br>"+
"<font color=#97AB40>"+model.getjob_location()+"," +
" "+model.getjob_exp_min()+"-"+model.getjob_exp_max()+" year";
holder.jobdetails.setText(Html.fromHtml(result));
}
return row;
}
class SearchResultHolder
{
TextView jobdetails;
}
}
My ListView in the Main Method That would use the Above ArrayAdapter.
SearchResultAdapter adapter;
ListView lv;
adapter=new SearchResultAdapter(this, R.layout.listitemrow, model);
//Here model is the ArrayList<SearchResultModel>
lv=getListView();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View v,int arg2, long arg3)
{
}
}
My SearchResultModel Class
package com.cws.model;
public class SearchResultModel {
private String job_id,userdetail_id,user_name,subuser_id,
job_title,search_keyword,job_skill,
job_exp_min,job_exp_max,
job_description,salary,
job_location,education,
industry_id,role_id,functional_id,job_type,
desire_candiadate_profile,company_profile,
website,executive_name,address,email,
phone,post_date,is_active;
private String count,counter;//----count=total no of row found
//---counter=now displaying row nos.
private String errorflag;
public void seterrorflag(String errorflag)
{
this.errorflag=errorflag;
}
public String geterrorflag()
{
return this.errorflag;
}
public void setcount(String count)
{
this.count=count;
}
public String getcount()
{
return this.count;
}
public void setcounter(String counter)
{
this.counter=counter;
}
public String getcounter()
{
return this.counter;
}
public void setjob_id(String job_id)
{
this.job_id=job_id;
}
public String getjob_id()
{
return this.job_id;
}
public void setuserdetail_id(String userdetail_id){
this.userdetail_id=userdetail_id;
}
public String getuserdetail_id()
{
return this.userdetail_id;
}
public void setuser_name(String user_name){
this.user_name=user_name;
}
public String getuser_name()
{
return this.user_name;
}
public void setsubuser_id(String subuser_id){
this.subuser_id=subuser_id;
}
public String getsubuser_id()
{
return this.subuser_id;
}
public void setjob_title(String job_title){
this.job_title=job_title;
}
public String getjob_title()
{
return this.job_title;
}
public void setsearch_keyword(String search_keyword){
this.search_keyword=search_keyword;
}
public String getsearch_keyword()
{
return this.search_keyword;
}
public void setjob_skill(String job_skill){
this.job_skill=job_skill;
}
public String getjob_skill()
{
return this.job_skill;
}
public void setjob_exp_min(String job_exp_min){
this.job_exp_min=job_exp_min;
}
public String getjob_exp_min()
{
return this.job_exp_min;
}
public void setjob_exp_max(String job_exp_max){
this.job_exp_max=job_exp_max;
}
public String getjob_exp_max()
{
return this.job_exp_max;
}
public void setjob_description(String job_description){
this.job_description=job_description;
}
public String getjob_description()
{
return this.job_description;
}
public void setsalary(String salary){
this.salary=salary;
}
public String getsalary()
{
return this.salary;
}
public void setjob_location(String job_location){
this.job_location=job_location;
}
public String getjob_location()
{
return this.job_location;
}
public void seteducation(String education){
this.education=education;
}
public String geteducation()
{
return this.education;
}
public void setindustry_id(String industry_id){
this.industry_id=industry_id;
}
public String getindustry_id()
{
return this.industry_id;
}
public void setrole_id(String role_id){
this.role_id=role_id;
}
public String getrole_id()
{
return this.role_id;
}
public void setfunctional_id(String functional_id){
this.functional_id=functional_id;
}
public String getfunctional_id()
{
return this.functional_id;
}
public void setjob_type(String job_type){
this.job_type=job_type;
}
public String getjob_type()
{
return this.job_type;
}
public void setdesire_candiadate_profile(String desire_candiadate_profile){
this.desire_candiadate_profile=desire_candiadate_profile;
}
public String getdesire_candiadate_profile()
{
return this.desire_candiadate_profile;
}
public void setcompany_profile(String company_profile){
this.company_profile=company_profile;
}
public String getcompany_profile()
{
return this.company_profile;
}
public void setwebsite(String website){
this.website=website;
}
public String getwebsite()
{
return this.website;
}
public void setexecutive_name(String executive_name){
this.executive_name=executive_name;
}
public String getexecutive_name()
{
return this.executive_name;
}
public void setaddress(String address){
this.address=address;
}
public String getaddress()
{
return this.address;
}
public void setemail(String email){
this.email=email;
}
public String getemail()
{
return this.email;
}
public void setphone(String phone){
this.phone=phone;
}
public String getphone()
{
return this.phone;
}
public void setpost_date(String post_date){
this.post_date=post_date;
}
public String getpost_date()
{
return this.post_date;
}
public void setis_active(String is_active){
this.is_active=is_active;
}
public String getis_active()
{
return this.is_active;
}
}

Categories

Resources