passing Data between FragmentA and FragmentB - android

How do you pass data between Fragments.
I've created a InstructionActivity, InstructionsFragment, StepsFragment and SharedViewModel. I'm trying to pass String from InstructionsFragment to the StepsFragment
this the result in my logCat:
D/StepsFragment:THIS com.shawn.nichol.bakingapp.Fragments.SharedViewModel#23e39c0
I have also put the whole code up on GitHub.
SharedViewModel:
public class SharedViewModel extends ViewModel {
private final MutableLiveData<String> stepPosition = new MutableLiveData<>();
public void setStepPosition(String position) {
stepPosition.setValue(position);
}
public MutableLiveData getStepPosition() {
return stepPosition;
}
}
InstructionsFragment:
public class InstructionsFragment extends Fragment {
private static final String LOGTAG = "InstructionsFragment";
private RecyclerView mRecyclerView;
private InstructionsAdapter mAdapter;
private String mAllIngredients;
private SharedViewModel model;
// Empty constructor
public InstructionsFragment() {
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle onSavedInstanceState) {
View view = inflater.inflate(R.layout.fragment_instructions, container, false);
model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
mRecyclerView = (RecyclerView) view.findViewById(R.id.ingredients_instructions_rv_fragments);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity().getApplicationContext(),
mRecyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
Log.d(LOGTAG, "Step " + (position + 1) + " " +
InstructionsExtractSteps.stepsShortDescriptionList.get(position));
model.setStepPosition("HELP");
FragmentManager mFragmentManager = getFragmentManager();
StepsFragment mStepsFragment = new StepsFragment();
FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction
.replace(R.id.instructions_place_holder, mStepsFragment)
// Puts InstructionsFragment on back stack, when back button is press it will
// reload that fragment instead of going back to the RecipeActivity.
.addToBackStack(null)
.commit();
}
#Override
public void onLongClick(View view, int position) {
}
}));
mAdapter = new InstructionsAdapter();
mRecyclerView.setAdapter(mAdapter);
return view;
}
/**
* onViewCreated: I found this to be the only way to update the TextView in fragment_instructions.xml
*
* #param view
* #param savedInstanceState
*/
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState){
TextView mLoadIngredients = (TextView)getView().findViewById(R.id.ingredients_tv_fragment);
// Set ingredients to screen
for(int i = 0; i < InstructionsExtractIngredients.ingredientList.size(); i++) {
if(i == 0) {
mAllIngredients = "- " + InstructionsExtractIngredients.ingredientList.get(i);
} else {
mAllIngredients = mAllIngredients + "\n - " + InstructionsExtractIngredients.ingredientList.get(i);
}
}
Log.d(LOGTAG, mAllIngredients);
mLoadIngredients.setText(mAllIngredients);
}
}
StepsFragment:
public class StepsFragment extends Fragment {
private static final String LOGTAG = "StepsFragment";
// Requires an empty constructor
public StepsFragment() {
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_step, container, false);
final SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
model.getStepPosition();
Log.d(LOGTAG, "THIS " + model);
return view;
}
}

you can use interfaces to allow communications between two fragment and its not deprecated
however a better alternative option is to use Architecture Components
just add the following libraries to your app gradle file
implementation 'android.arch.lifecycle:extensions:1.1.1'
implementation 'android.arch.lifecycle:runtime:1.1.1'
and then create the following class as shown below
import android.arch.lifecycle.ViewModel;
import android.support.annotation.NonNull;
public class TestViewModel extends ViewModel {
private MutableLiveData<String> fragmentAClicked;
public LiveData<String> getFragmentAClicked() {
if (fragmentAClicked == null) {
fragmentAClicked = new MutableLiveData<String>();
}
return fragmentAClicked;
}
public void fragmentAIsClicked(){
fragmentAClicked.setValue("I am clicked")
}
}
in your activity class add the following code
public class MyActivity extends AppCompatActivity {
TestViewModel model;
public void onCreate(Bundle savedInstanceState) {
model = ViewModelProviders.of(this).get(TestViewModel.class);
}
}
suppose you have two fragments A and B
public class FragmentB extends Fragment {
private TestViewModel model;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
model =ViewModelProviders.of(getActivity()).get(TestViewModel.class);
//communicating with fragment
model.fragmentAIsClicked();
}
}
public class FragmentA extends Fragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TestViewModel model = ViewModelProviders.of(getActivity()).get(TestViewModel.class);
model.getFragmentAClicked().observe(this, { msg ->
Log.d("test","message from fragmentA is " + msg)
});
}
}
so basically the idea is that you a viewmodel class based on mvvm design pattern which handles all communication between activities ,fragments using events
for more info check this viewmodel

I don't know what is your purpose but you can use a POJO class to pass between fragment.
public class Test {
public static class FragmentScanIDGInfo {
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
String lastName = "";
String firstName = "";
public static FragmentScanIDGInfo shared;
public static FragmentScanIDGInfo sharedSingleton() {
if (shared == null) {
shared = new FragmentScanIDGInfo();
}
return shared;
}
FragmentScanIDGInfo() {
this.setLastName("");
this.setFirstName("");
}
}
}
And you can set and get in your own purpose like :
Test.FragmentScanIDGInfo scanDataFragment = Test.FragmentScanIDGInfo.sharedSingleton();
scanDataFragment.setFirstName(""); /* set data first name */
scanDataFragment.getFirstName(); /* get data first name */

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

How to pass an Object from one fragment to other fragment

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

How to create a list dialog using Dialogfragment and ArrayAdapter to populate items from Java class?

I am learning DialogFragments myself. I have never tried anything than passing intent from a Button, so I am not getting to right direction.
I want to learn all the possible ways.
Is it different than creating a list with ListFragment?
There are 2 buttons on main Activity. On clicking the second Button, it should open a DialogFragment with a list of items, clicking on a list item should open a URL in the browser.
Main Activity
btnDepartment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent intent = new Intent(MainActivity.this, DepartmentActivity.class);
//startActivity(intent);
}
});
Here is Department Class, which is a pure Java class
public class Department {
private String deptName, deptUrl;
public static final Department[] myDepartment = {
new Department("CS", "http://cs.com"),
new Department("Biology", "http://bio.com"),
new Department("Chemistry", "http://www.chemistry.com"),
new Department("Nursing", "http://nursing.com")
};
private Department(String deptName, String deptUrl){
this.deptName = deptName;
this.deptUrl = deptUrl;
}
public String getDeptName() {
return deptName;
}
public String getDeptUrl() {
return deptUrl;
}
#Override
public String toString() {
return deptName;
}
}
Department Fragment
public class DepartmentFragment extends DialogFragment {
public DepartmentFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_department, container, false);
}
}
Is [creating a DialogFragment] different than creating list with ListFragment
Simply: Yes.
Why? Because ListFragment gives you access to both getListView() and setAdapter() and instance methods of the class.
In order to do that with any other Fragment class that does not extend from ListFragment, you must declare some XML layout with a ListView and do something like this
I'll assume fragment_department.xml contains a ListView element of #+id/list and that you do not care about how the Department information is displayed.
public class DepartmentFragment extends DialogFragment {
public DepartmentFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_department, container, false);
ListView lstView = (ListView) rootView.findViewById(R.id.list);
ArrayAdapter<Department> adapter = new ArrayAdapter<Department>(getActivity(), android.R.layout.simple_list_item_1, Department.myDepartment);
lstView.setAdapter(adapter);
// TODO: adapter.setOnItemClickListener
// ... handle click
// ... load webpage
return rootView;
}
}
First, your model must implements Parcelable:
public class Department implements Parcelable {
private String deptName, deptUrl;
public static final Department[] myDepartment = {
new Department("CS", "http://cs.com"),
new Department("Biology", "http://bio.com"),
new Department("Chemistry", "http://www.chemistry.com"),
new Department("Nursing", "http://nursing.com")
};
private Department(String deptName, String deptUrl){
this.deptName = deptName;
this.deptUrl = deptUrl;
}
protected Department(Parcel in) {
deptName = in.readString();
deptUrl = in.readString();
}
public static final Creator<Department> CREATOR = new Creator<Department>() {
#Override
public Department createFromParcel(Parcel in) {
return new Department(in);
}
#Override
public Department[] newArray(int size) {
return new Department[size];
}
};
public String getDeptName() {
return deptName;
}
public String getDeptUrl() {
return deptUrl;
}
#Override
public String toString() {
return deptName;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(deptName);
parcel.writeString(deptUrl);
}
}
After, you must implement the method:
btnDepartment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DepartmentFragment departmentFragment = DepartmentFragment.newInstance(department);
departmentFragment.show(getSupportFragmentManager(), "departmentFragment");
}
});
And the fragment as follows:
public class DepartmentFragment extends DialogFragment {
private Department department;
public DepartmentFragment() {
// Required empty public constructor
}
public static DepartmentFragment newInstance(Department department) {
DepartmentFragment f = new DepartmentFragment();
// Supply num input as an argument.
Bundle extras = new Bundle();
args.putParcelable("department", department);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
department = getArguments().getParcelable("department")
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_department, container, false);
}
}
Also, you can check all information at http://developer.android.com/reference/android/app/DialogFragment.html

on one Fragment it gets value on other in same way created Fragment gets null

Im using JSON files to store data and Im creating ListFragment which is populated by Listviews which gets that data. And I need to extract it or store it on AddFragment, ViewFragment and its being sorted by UUID and it works fine on ViewFragment just AddFragment gets null on cloud value. Any Ideas where should I look for problems or how to solve it?
ViewFragment: cloud = CloudLab.get(getActivity()).getCloud(dreamIds); returns right value.
public class ViewFragment extends Fragment{
public static final String EXTRA_DREAMEE_ID = "com.example.tadas.dreamcload1.dream_id";
private Cloud cloud;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID dreamIds = (UUID)getArguments().getSerializable(EXTRA_DREAMEE_ID);
cloud = CloudLab.get(getActivity()).getCloud(dreamIds);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_view, parent, false);
return v;
}
public static ViewFragment newInstance(UUID dreamIds) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DREAMEE_ID, dreamIds);
ViewFragment fragment = new ViewFragment();
fragment.setArguments(args);
return fragment;
}
}
But in AddFragment dCloud = CloudLab.get(getActivity()).getCloud(dreamId); returns null.
public class AddFragment extends Fragment {
private static final String TAG = "CloadLab";
public static final String EXTRA_DREAM_ID = "com.example.tadas.dreamcload1.dream_id";
private Cloud dCloud;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
UUID dreamId = (UUID)getArguments().getSerializable(EXTRA_DREAM_ID);
dCloud = CloudLab.get(getActivity()).getCloud(dreamId);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_add,parent,false);
return v;
}
public static AddFragment newInstance(UUID dreamId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DREAM_ID, dreamId);
AddFragment fragment = new AddFragment();
fragment.setArguments(args);
return fragment;
}
}
CloudLab class
public class CloudLab {
private static final String TAG = "CloudLab";
private static final String FILENAME = "dre.json";
private ArrayList<Cloud> mClouds;
private DreamCloudSerializer mSerializer;
private static CloudLab sCloudLab;
private Context mAppContext;
public CloudLab(Context appContext) {
mAppContext = appContext;
mSerializer = new DreamCloudSerializer(mAppContext, FILENAME);
try {
mClouds = mSerializer.loadDre();
}catch (Exception e) {
mClouds = new ArrayList<Cloud>();
Log.e(TAG, "Error loading: ", e);
}
}
public static CloudLab get(Context c) {
if (sCloudLab == null) {
sCloudLab = new CloudLab(c.getApplicationContext());
}
return sCloudLab;
}
public void addDre(Cloud c) {
mClouds.add(c);
}
public void deleteDre(Cloud c) {
mClouds.remove(c);
}
public boolean saveDre() {
try {
mSerializer.saveDre(mClouds);
Log.d(TAG, "saved to file");
return true;
} catch (Exception e) {
Log.e(TAG, "Error saving: ", e);
return false;
}
}
public ArrayList<Cloud> getClouds() {
return mClouds;
}
public Cloud getCloud(UUID id) {
for (Cloud c : mClouds) {
if (c.getId().equals(id))
return c;
}
return null;
}
Your fragments are not exactly the same. You have different dream ids and are expecting same result.
// your id in ViewFragment
public static final String EXTRA_DREAMEE_ID = "com.example.tadas.dreamcload1.dream_ids";
// your id in AddFragment
public static final String EXTRA_DREAM_ID = "com.example.tadas.dreamcload1.dream_id";
// strings for your dream id in each fragment is different
Both strings are different. If you expect same result, pass same id. Or make sure both these ids when passed - exist and have same content.

Android getActivity().setTitle() gets String field from wrong object in ArrayList

I wish to set the titlebar in this fragment's activity to the HelpItem's description field.
On line 10, I set the title of the activity with a String representing a HelpItem's description.
Instead of getting the description of the retrieved HelpItem on line 9 I get the description of the next HelpItem.
I.E. in an ArrayList of five HelpItem objects with the helpDescriptions "aaa", "bbb", "ccc", "ddd", "eee" clicking on "bbb" in the
list displays "bbb" and the information text associated with it. The title is set to "ccc".
On line 19 the same call to helpItem.getHelpDescription() returns the description field of the "bbb" object.
When moving through the list via a ViewPager the next object in the list has the same issue until I reach the end of the list,
where the correct helpDescription field is displayed. I can also move back to the start of the list and it will display the correct
helpDescription, but this is then lost when I move forward and backward through the list again.
Any ideas why this is happening? Thanks.
public class HelpFragment extends Fragment {
private HelpItem helpItem;
private TextView mHelpDetails;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
UUID helpItemId = (UUID) getArguments().getSerializable(EXTRA_HELP_ITEM_ID);
helpItem = HelpList.get(getActivity()).getHelpItem(helpItemId);
getActivity().setTitle(helpItem.getHelpDescription());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View userView = inflater.inflate(R.layout.fragment_help_item, parent, false);
mHelpDetails = (TextView) userView.findViewById(R.id.help_details);
String displayInfo = "";
if ((helpItem.getHelpDescription() != null) &&
(helpItem.getHelpInformation() != null)) {
displayInfo = helpItem.getHelpDescription() + "\n\n\n" +
helpItem.getHelpInformation();
mHelpDetails.setText(displayInfo);
Log.d(TAG, "3 " + helpItem.getHelpDescription() + " "
+ helpItem.getHelpInformation());
}
return userView;
}
}
..
public class HelpItem {
private UUID mId;
private String helpDescription;
private String helpInformation;
public HelpItem(String hDesc, String hInfo) {
mId = UUID.randomUUID();
helpDescription = hDesc;
helpInformation = hInfo;
}
public UUID getId() {
return mId;
}
public void setId(UUID id) {
mId = id;
}
#Override
public String toString() {
return helpDescription;
}
public String getHelpDescription() {
return helpDescription;
}
public void setHelpDescription(String hDescription) {
this.helpDescription = hDescription;
}
public String getHelpInformation() {
return helpInformation;
}
public void setHelpInformation(String hInformation) {
this.helpInformation = hInformation;
}
}
..
public class HelpListItemPagerActivity extends FragmentActivity {
private ViewPager mViewPager;
private ArrayList<HelpItem> mHelpList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.viewPager);
setContentView(mViewPager);
mHelpList = HelpList.get(this).getHelpList();
FragmentManager fragManager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragManager) {
#Override
public int getCount() {
return mHelpList.size();
}
#Override
public Fragment getItem(int position) {
HelpItem hItem = mHelpList.get(position);
return HelpFragment.newInstance(hItem.getId());
}
});
UUID helpItemId = (UUID)getIntent().getSerializableExtra(HelpFragment.EXTRA_HELP_ITEM_ID);
for (int i = 0; i < mHelpList.size(); i++) {
if (mHelpList.get(i).getId().equals(helpItemId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}

Categories

Resources