How to pass an Object from one fragment to other fragment - android

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

Related

RecyclerView, each items has its own activity

I have a RecyclerView, it has items in it. I need each item to have its own Activity, that is, we have item1 by clicking on it, Activity1 opens, there is also item2 about clicking on it, Activity2 is opened. Can this be done somehow? If so, how? I managed to make it so that when I clicked, the same Fragment opened, and the text changes depending on which item was clicked. But it doesn't quite suit me.
Fragment where the RecyclerView is located
public class FragmentAttractionRecyclerView extends Fragment {
private RecyclerView mRec;
private AttractionsAdapter adapter;
private ArrayList<AttractionsItem> exampleList;
private RecyclerView.LayoutManager mLayoutManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_attraction_test_2, container, false);
}
#SuppressLint("InflateParams")
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
createExampleList();
buildRecyclerView();
}
public void createExampleList() {
exampleList = new ArrayList<>();
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Baby островок", "Детский", "60₽","Максимальное кол-во детей","10","Возраст","С 1-го до 6 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Виражи", "Детский", "80₽","Максимальное кол-во пассажиров","24", "Возраст","От 4-х до 12 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Вокруг света", "Детский", "50₽","Максимальное кол-во пассажиров","12","Возраст","От 3-х до 12 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_interactive, "5D кинотеатр", "Интерактивный", "120₽","Максимальное кол-во пассажиров","","Возраст","С 6 лет"));
}
public void buildRecyclerView() {
mRec = requireView().findViewById(R.id.attraction_recycler);
adapter = new AttractionsAdapter(exampleList);
mLayoutManager = new LinearLayoutManager(getContext());
mRec.setLayoutManager(mLayoutManager);
mRec.setAdapter(adapter);
}
}
Adapter for RecyclerView
public class AttractionsAdapter extends RecyclerView.Adapter<AttractionsAdapter.AttractionsViewHolder> {
public ArrayList<AttractionsItem> mFavList;
public AttractionsAdapter(ArrayList<AttractionsItem> favList) {
mFavList = favList;
}
#NonNull
#Override
public AttractionsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_attraction, parent, false);
AttractionsViewHolder evh = new AttractionsViewHolder(v);
return evh;
}
public static class AttractionsViewHolder extends RecyclerView.ViewHolder {
public ImageView card_image_1, card_image_2;
public TextView card_text_1, card_text_2, card_text_3,attraction_menu_1_1,attraction_menu_1_2;
public CardView Card;
public AttractionsViewHolder(View itemView) {
super(itemView);
card_image_1 = itemView.findViewById(R.id.card_image_1);
card_image_2 = itemView.findViewById(R.id.card_image_2);
card_text_1 = itemView.findViewById(R.id.card_text_1);
card_text_2 = itemView.findViewById(R.id.card_text_2);
card_text_3 = itemView.findViewById(R.id.card_text_3);
attraction_menu_1_1 = itemView.findViewById(R.id.attraction_menu_1_1);
attraction_menu_1_2 = itemView.findViewById(R.id.attraction_menu_1_2);
Card = itemView.findViewById(R.id.Card);
}
}
#Override
public void onBindViewHolder(AttractionsViewHolder holder, int position) {
AttractionsItem currentItem = mFavList.get(position);
holder.card_image_1.setImageResource(currentItem.getImg1());
holder.card_image_2.setImageResource(currentItem.getImg2());
holder.card_text_1.setText(currentItem.get_attraction_name());
holder.card_text_2.setText(currentItem.get_attraction_type());
holder.card_text_3.setText(currentItem.get_attraction_cost());
holder.Card.setOnClickListener(v -> {
FragmentBlancAttraction fragment = new FragmentBlancAttraction(); // you fragment
FragmentManager fragmentManager = ((FragmentActivity) v.getContext()).getSupportFragmentManager(); // instantiate your view context
Bundle bundle = new Bundle();
bundle.putString("name", currentItem.get_attraction_name());
bundle.putString("menu_1_1", currentItem.get_attraction_menu_1_1());
bundle.putString("menu_1_2", currentItem.get_attraction_menu_1_2());
bundle.putString("menu_2_1", currentItem.get_attraction_menu_2_1());
bundle.putString("menu_2_2", currentItem.get_attraction_menu_2_2());
fragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.animator.nav_default_enter_anim, R.animator.nav_default_exit_anim,
R.animator.nav_default_pop_enter_anim, R.animator.nav_default_pop_exit_anim);
fragmentTransaction.replace(R.id.fragment, fragment);// your container and your fragment
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
});
}
#Override
public int getItemCount() {
return mFavList.size();
}
}
public class AttractionsItem
{
private int mImg_1,mImg_2;
private final String mText_attraction_name;
private final String mText_attraction_type;
private final String mText_attraction_cost;
private final String mText_attraction_menu_1_1;
private final String mText_attraction_menu_1_2;
private final String mText_attraction_menu_2_1;
private final String mText_attraction_menu_2_2;
public AttractionsItem(int img1,int img2, String text_attraction_name, String text_attraction_type, String text_attraction_cost, String text_attraction_menu_1_1, String text_attraction_menu_1_2, String text_attraction_menu_2_1, String text_attraction_menu_2_2)
{
mImg_1 = img1;
mImg_2 = img2;
mText_attraction_name = text_attraction_name;
mText_attraction_type = text_attraction_type;
mText_attraction_cost = text_attraction_cost;
mText_attraction_menu_1_1 = text_attraction_menu_1_1;
mText_attraction_menu_1_2 = text_attraction_menu_1_2;
mText_attraction_menu_2_1 = text_attraction_menu_2_1;
mText_attraction_menu_2_2 = text_attraction_menu_2_2;
}
public int getImg1()
{
return mImg_1;
}
public int getImg2()
{
return mImg_2;
}
public String get_attraction_name()
{
return mText_attraction_name;
}
public String get_attraction_type()
{
return mText_attraction_type;
}
public String get_attraction_cost()
{
return mText_attraction_cost;
}
public String get_attraction_menu_1_1()
{
return mText_attraction_menu_1_1;
}
public String get_attraction_menu_1_2()
{
return mText_attraction_menu_1_2;
}
public String get_attraction_menu_2_1()
{
return mText_attraction_menu_2_1;
}
public String get_attraction_menu_2_2()
{
return mText_attraction_menu_2_2;
}
}
The positon param inside onBindViewHolder() method tells you which item of your RecyclerView clicked.
Use this to control your program and in out of onBindViewHolder() method you can get your item position by getAdapterPosition().
holder.Card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (position) {
case 0: {
// Start first activity.
break;
}
case 1: {
// Start Second activity.
break;
}
}
}
});

Dynamic Tabs with dynamic data in viewpager fragment

I need a help. I am developing dynamic tabs with dynamic data in viewpager fragment's list. Somehow i got the dynamic tabs and hit API in placeholder fragment to get the recyclerview list.
there are two issue. 1. design is overlapping the tabs and 2. its loading 3rd id data first.
here is the code.
here is main class
public class NewsFeed extends Fragment {
private static RecyclerView listView;
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private TabLayout tabLayout;
private ViewPager viewPager;
private RecyclerView recyclerView;
private ApiInterface apiInterface;
private List<BlogCatData> list = new ArrayList<BlogCatData>();
private BlogCatListAdaptor adapter;
private String item;
private ArrayList<BlogCatData> dataModelList = new ArrayList<BlogCatData>();
private ArrayList<String> CatTitleList = new ArrayList<>();
private static ArrayList<String> CatIdList = new ArrayList<>();
private View view1;
private View v;
// private ArrayAdapter<BlogCatData> adapter;
public NewsFeed() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_news_feed, container, false);
getAllBlogCat();
return v;
}
private void setViewIDs() {
tabLayout = v.findViewById(R.id.tabs);
viewPager = v.findViewById(R.id.container);
setUpViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
private void getAllBlogCat() {
// avi.show();
apiInterface = APIClient.getClient().create(ApiInterface.class);
Call<BlogCatModel> call = apiInterface.GETBlogCategory();
call.enqueue(new Callback<BlogCatModel>() {
#Override
public void onResponse(Call<BlogCatModel> call, retrofit2.Response<BlogCatModel> response) {
if (response.isSuccessful()) {
CatIdList.clear();
list = response.body().getDATA();
for (int i = 0; i < list.size(); i++) {
CatTitleList.add(list.get(i).getTITLE());
CatIdList.add(list.get(i).getID());
}
Log.v("CatTitle", CatTitleList.toString());
Log.v("CatId", CatIdList.toString());
setViewIDs();
// adapter.setPostList(list)
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getApplicationContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<BlogCatModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
private void setUpViewPager(ViewPager viewPager) {
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
for (int i = 0; i < CatTitleList.size(); i++) {
Bundle bundle = new Bundle();
bundle.putString("id", CatIdList.get(i));
PlaceholderFragment categoryList = new PlaceholderFragment();
categoryList.setArguments(bundle);
sectionsPagerAdapter.addFragment(categoryList, CatTitleList.get(i));
}
sectionsPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(sectionsPagerAdapter);
}
public static class PlaceholderFragment extends Fragment {
private final static String TAG = PlaceholderFragment.class.getSimpleName();
private static String item;
private static ArrayList<String> dataModelList = new ArrayList<String>();
// private ArrayAdapter<Model> adapter;
private RecyclerView listView;
private List<BlogData> dataList = new ArrayList<>();
private BlogListAdaptor blogListAdaptor;
private static String id;
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
id = CatIdList.get(sectionNumber);
Bundle args = new Bundle();
args.putString("ID", id);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment__newsfeed_placeholder, container, false);
listView = view.findViewById(R.id.recycler_view);
getBlog(Id);
setBlog();
return view;
}
private void getBlog(String id) {
ApiInterface apiInterface = APIClient.getClient().create(ApiInterface.class);
Call<BlogModel> call = apiInterface.getNewsByCategory(id);
call.enqueue(new Callback<BlogModel>() {
#Override
public void onResponse(Call<BlogModel> call, retrofit2.Response<BlogModel> response) {
if (response.isSuccessful()) {
dataList = response.body().getDATA();
blogListAdaptor.setPostList(dataList);
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getApplicationContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<BlogModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
private void setBlog() {
blogListAdaptor = new BlogListAdaptor(getActivity(), dataList);
listView.setAdapter(blogListAdaptor);
listView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
listView.setLayoutManager(linearLayoutManager);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 0);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public int getCount() {
return mFragmentTitleList.size();
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
}
return mFragmentTitleList.get(position);
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
}
}
and here is the adapter class for recyclerview
public class BlogListAdaptor extends RecyclerView.Adapter<BlogListAdaptor.MyViewHlder> {
private Activity activity;
private List<BlogData> list;
private boolean valid;
private EditText name, email, phone, date, noOfGuest, msg;
private Spinner partyMode, timeSlot;
private AlertDialog alertDialog;
final Calendar myCalendar = Calendar.getInstance();
private String PartyModeStr, TimeSlotStr;
private String Id;
private String title;
public BlogListAdaptor(Activity activity, List<BlogData> list) {
this.activity = activity;
this.list = list;
}
public void setPostList(List<BlogData> dataList) {
list = dataList;
notifyDataSetChanged();
}
#NonNull
#Override
public MyViewHlder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.blog_list_layout, viewGroup, false);
MyViewHlder my = new MyViewHlder(view);
return my;
}
#Override
public void onBindViewHolder(#NonNull MyViewHlder myViewHlder, int i) {
myViewHlder.Title.setText(list.get(i).getTITLE());
myViewHlder.Author.setText(list.get(i).getAUTHOR());
if (list.get(i).getIMGSRC() != null)
Glide.with(activity).load(Constant.ImgRoot + list.get(i).getIMGSRC())
.into(myViewHlder.Image);
myViewHlder.cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(activity, DetailActivity.class);
intent.putExtra("Id", list.get(i).getID());
intent.putExtra("Title", list.get(i).getTITLE());
intent.putExtra("Author", list.get(i).getAUTHOR());
intent.putExtra("Content", list.get(i).getCONTENT());
activity.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHlder extends RecyclerView.ViewHolder {
private TextView Title, Author;
private ImageView Image;
private CardView cardview;
public MyViewHlder(#NonNull View itemView) {
super(itemView);
Image = itemView.findViewById(R.id.image);
Title = itemView.findViewById(R.id.title);
Author = itemView.findViewById(R.id.author);
cardview = itemView.findViewById(R.id.cardview);
}
}
}
Please help me out, to call api...
fragment_newsfeed_placeholder
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
fragment_news_feed
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabGravity="center"
app:tabMode="scrollable"
app:tabTextColor="#ffffff" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tabs" />

ViewPager returns wrong Object

The pager returns the 1st object in the array list, and keeps returning the 1st object even if i swing left and right, did a lot of debugging, and for some reason when the pager get's to getItem(int position) it start's going crazy, it FINDS the corresponding object , then looks a the previous object(pos-1) then does some other weird things and returns the 1st obj in arrayList.
This method is called within the ViewHolder of RecyclerViewAdapter
#Override
public void onClick(View v) {
Intent i = ProductPageActivity.newIntent(v.getContext(),mProduct.getId());
v.getContext().startActivity(i);
}
}
public class ProductFragment extends Fragment {
private static final String TAG = "ProductFragment";
private static final String ARGUMENT_PROD_ID = "prod_id";
private TextView mTitle,mDesc,mImgUrl,mPrice;
private List<Product> mProducts;
private Product product;
public static Fragment newInstance(UUID productID) {
Bundle args = new Bundle();
args.putSerializable(ARGUMENT_PROD_ID,productID);
ProductFragment frag = new ProductFragment();
frag.setArguments(args);
return frag;
}
public ProductFragment() {}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments() != null) {
UUID id = (UUID) getArguments().getSerializable(ARGUMENT_PROD_ID);
product = ProductHolder.get(getContext()).getProduct(id);
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.product_fragment,container,false);
setWidgets(v);
setDataOnText();
return v;
}
private void setDataOnText(){
mTitle.setText(product.getTitle());
mDesc.setText(product.getDesc());
mPrice.setText(product.getPrice());
}
private void setWidgets(View v) {
mTitle = (TextView) v.findViewById(R.id.title);
mDesc = (TextView) v.findViewById(R.id.desc);
mPrice = (TextView) v.findViewById(R.id.price);
}
}
public class ProductPageActivity extends AppCompatActivity {
private static final String PRODUCT_ID = "com.example.cmd.testproject.Activitys.ProductPageActivity.product_id";
private UUID productId;
private ViewPager mPager;
private List<Product> mProducts;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_page_activity);
productId = (UUID) getIntent().getSerializableExtra(PRODUCT_ID);
mPager = (ViewPager) findViewById(R.id.viewPager);
mProducts = ProductHolder.get(this).getProducts();
FragmentManager fragmentManager = getSupportFragmentManager();
mPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
Product pr = mProducts.get(position);
return ProductFragment.newInstance(pr.getId());
}
#Override
public int getCount() {
return mProducts.size();
}
});
for (int i = 0; i < mProducts.size(); i++) {
if (mProducts.get(i).getId().equals(productId)) {
mPager.setCurrentItem(i);
break;
}
}
}
public static Intent newIntent(Context packageContext, UUID productID) {
Intent intent = new Intent(packageContext, ProductPageActivity.class);
intent.putExtra(PRODUCT_ID, productID);
return intent;
}
}
public class ProductHolder {
private static final String TAG = "ProductHolder";
private static ProductHolder sProductHolder;
private List<Product> mProducts;
public static ProductHolder get(Context ctx) {
if(sProductHolder == null) {
sProductHolder = new ProductHolder(ctx);
}
return sProductHolder;
}
private ProductHolder(Context ctx) {
mProducts = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Product product = new Product("Product = " + i, "Desc = "
+ i, "ImgUrl = " + i, "Price = " + i + 2.2);
mProducts.add(product);
}
}
public Product getProduct(UUID prodId) {
for (Product pr:mProducts) {
if(pr.getId().equals(prodId));
return pr;
}
return null;
}
public List<Product> getProducts() {
return mProducts;
}
}

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

RecyclerView save elements in JSON

I have recyclerview (in fragment) and fragment with details information to one of the element. All is good, but when my data was saved. I have bad results in my JSON file. All times when i open element of list he add new element inside JSON file, while he must overwrite oneself.
My Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_page_activity);
Log.i("MainActivity", "onCreate");
if(savedInstanceState==null) {
getFragment(new ObjectListFragment());
}
}
public void getFragment(Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
if (mFragment == null) {
mFragment = fragment;
fm.beginTransaction()
.add(R.id.fragment_container, mFragment)
.commit();
}
if (mFragment != null) {
mFragment = fragment;
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
}
}
My Model:
public class Object {
private static final String JSON_ID = "id";
private static final String JSON_TITLE = "title";
private UUID mId;
private String mTitle;
public Object() {
mId=UUID.randomUUID();
}
public Object(JSONObject json) throws JSONException {
mId = UUID.fromString(json.getString(JSON_ID));
mTitle = json.getString(JSON_TITLE);
}
public JSONObject toJSON()throws JSONException{
JSONObject json = new JSONObject();
json.put(JSON_ID, mId.toString());
json.put(JSON_TITLE, mTitle);
return json;
}
public UUID getId() {
return mId;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
#Override
public String toString() {
return mTitle;
}
}
ObjectLab:
public class ObjectLab {
private static final String TAG = "ObjectLab";
private static final String FILENAME = "reminder.json";
private ObjectJSON mSerializer;
private ArrayList<Object> mObjects;
private static ObjectLab sObjectLab;
private Context mContext;
private ObjectLab(Context context){
mContext = context;
mSerializer = new ObjectJSON(mContext, FILENAME);
try {
mObjects = mSerializer.loadReminders();
} catch (Exception e) {
mObjects = new ArrayList<Object>();
Log.e(TAG, "Error loading crimes: ", e);
}
}
public static ObjectLab get(Context c){
if(sObjectLab == null){
sObjectLab = new ObjectLab(c.getApplicationContext());
}
return sObjectLab;
}
public ArrayList<Object> getObjects(){
return mObjects;
}
public Object getReminder(UUID id){
for(Object c : mObjects){
if(c.getId().equals(id))
return c;
}
return null;
}
public void addReminder(Object c){
mObjects.add(0,c);
}
public void deleteReminder(Object c){
mObjects.remove(c);
}
public boolean saveReminders(){
try{
mSerializer.saveReminders(mObjects);
Log.d(TAG, "reminders saved to file");
return true;
}catch (Exception e){
Log.e(TAG, "Error saving crimes: ", e);
return false;
}
}
ObjectJSON:
public class ObjectJSON {
private Context mContext;
private String mFilename;
public ObjectJSON(Context context, String filename) {
mContext = context;
mFilename = filename;
}
public void saveReminders(ArrayList<Object> objects) throws JSONException, IOException {
Log.i("Save","saveReminders");
JSONArray array = new JSONArray();
for (Object f : objects)
array.put(f.toJSON());
Writer writer = null;
try {
OutputStream out = mContext.openFileOutput(mFilename, Context.MODE_APPEND);
writer = new OutputStreamWriter(out);
writer.write(array.toString());
} finally {
if (writer != null)
writer.close();
}
}
public ArrayList<Object> loadReminders() throws IOException, JSONException {
Log.i("Save","loadReminders");
ArrayList<Object> objects = new ArrayList<Object>();
BufferedReader reader = null;
try {
InputStream in = mContext.openFileInput(mFilename);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
jsonString.append(line);
}
JSONArray array = (JSONArray) new JSONTokener(jsonString.toString())
.nextValue();
for (int i = 0; i < array.length(); i++) {
objects.add(new Object(array.getJSONObject(i)));
}
} catch (FileNotFoundException e) {
//when 0
} finally {
if (reader != null)
reader.close();
}
return objects;
}
ObjectListFragment:
public class ObjectListFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerAdapter mAdapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.reminder_activity, container, false);
Log.i("ObjectListFragment", "onCreateView");
final ArrayList<Object> mData = ObjectLab.get(getActivity()).getObjects();
getActivity().setTitle("Object");
mRecyclerView = (RecyclerView)v. findViewById(R.id.my_recycler_view);
//registerForContextMenu(mRecyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(mData);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(v.getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Log.i("ObjectListFragment", "onItemClick");
Object f = mData.get(position);
FragmentManager fm = getFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
Bundle bundle = new Bundle();
bundle.putSerializable(ObjectFragment.EXTRA_REMINDER_ID, f.getId());
if (mFragment != null) {
mFragment = new ObjectFragment();
mFragment.setArguments(bundle);
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
}
}));
return v;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Log.d("Testing", "ID == " + id);
switch (id) {
case R.id.action_settings: {
Log.d("onOptionsItemSelected", " SETTings");
Object f = new Object();
ObjectLab.get(getActivity()).addReminder(f);
FragmentManager fm = getFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
Bundle bundle = new Bundle();
bundle.putSerializable(ObjectFragment.EXTRA_REMINDER_ID, f.getId());
if (mFragment != null) {
mFragment = new ObjectFragment();
mFragment.setArguments(bundle);
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
return true;
}
}
return super.onOptionsItemSelected(item);
}
}
RecyclerAdapter:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
ArrayList<Object> mData;
public RecyclerAdapter(ArrayList<Object> objects) {
mData = objects;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.reminder_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTitleTextView.setText(mData.get(position).getTitle());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView mTitleTextView;
public ViewHolder(View itemView) {
super(itemView);
mTitleTextView = (TextView) itemView.findViewById(R.id.forget_list_titleTextView);
}
}
RecyclerItemClickListener:
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildLayoutPosition(childView));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
and last ObjectFragmet
public class ObjectFragment extends Fragment{
public static final String EXTRA_REMINDER_ID = "id";
private Object mObject;
public static ObjectFragment newInstance(UUID crimeId) {
Log.i("ObjectFragment", "newInstance");
Bundle args = new Bundle();
args.putSerializable(EXTRA_REMINDER_ID, crimeId);
ObjectFragment fragment = new ObjectFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID uuid = (UUID) getArguments().getSerializable(EXTRA_REMINDER_ID);
Log.i("ObjectFragment", " "+uuid);
mObject = ObjectLab.get(getContext()).getReminder(uuid);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.remind_act, container, false);
EditText editText = (EditText)v.findViewById(R.id.editText1);
editText.setText(mObject.getTitle());
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
mObject.setTitle(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return v;
}
#Override
public void onPause() {
super.onPause();
Log.i("ObjectFragment", "onPause");
ObjectLab.get(getActivity()).saveReminders();
}
Links to the project(Android Studio).
Where my problem is that I do not. With pleasure hear all your comments and advice on the topic as well as that off-topic.
Your help will not forsake unattended.
When opening the OutputStream for writing into the file, you're using the Context.MODE_APPEND flag, which is causing the write operation to append and not overwrite as you intended, change it to:
OutputStream out = mContext.openFileOutput(mFilename, 0);
Also, there was no need to mention the RecyclerView at all, since it has nothing to do with the problem at hand.

Categories

Resources