How to refresh the fragment onResume - java

I am a newbie in Android development. I am facing an issue. I need some help from you guys.
Firstly, I am working on an application that is similar to BookMyShow.
I have an activity that contains a fragment. The activity contains a list of timeslots in a recycler view.
When I click on one of the timeslots, I go to new activity where I book the show with the specific details like username, id, timeslot_selected, etc and once he submits the "SUBMIT" button in the activity, it should come back to the same fragment that he was in, earlier, and show his details on the fragment. Initial there is nobody in the recycler view, now the user should see himself in that recycler view at the selected timeSlot as an icon.
I have the next button as well. When the user clicks on it, I am replacing the fragment with the following date. If the user clicks on one of the slots, he would be redirected to the same booking activity and once he submits, he should come back to the previous fragment with the same date that he was on earlier and with an updated icon of himself.
Now, I am unable to show that updated icon in the previous fragment once he clicks submit on the booking activity. Can you please suggest what should I do?
I tried detaching and attaching the fragment but to no avail. Please help me with a solution. Thanks in Advance!
SampleActivity.java:
public class SampleActivity extends AppCompatActivity {
TextView text;
Person person;
String id, name, date;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
Intent intent = getIntent();
id = intent.getStringExtra("id");
name= intent.getStringExtra("name");
date= intent.getStringExtra("date");
person= (Person) getIntent().getSerializableExtra("person");
text= findViewById(R.id.name);
text.setText(name);
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
bundle.putString("date", date);
bundle.putSerializable("Person", person);
FragmentA newFragment = new FragmentA();
newFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.mainFrameLayout, newFragment, "main_fragment").commit();
}
FragmentA.java:
public class FragmentA extends Fragment implements View.OnClickListener {
RecyclerView recyclerView;
public FragmentA() {
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_new, container, false);
recyclerView = view.findViewById(R.id.slots);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
requestQueue = VolleySingleton.getmInstance(getActivity()).getRequestQueue();
newList = new ArrayList<>();
next = view.findViewById(R.id.nextButton);
timeView = view.findViewById(R.id.timeOn);
dateText= view.findViewById(R.id.date);
Bundle bundle = getArguments();
assert bundle != null;
id= bundle.getString("id");
name = bundle.getString("name");
date = bundle.getString("date");
person = (Person) bundle.getSerializable("Person");
next.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
if (v.getId()== R.id.nextButton) {
replaceFragment();
}
}
private void replaceFragment() {
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
bundle.putString("date", date);
bundle.putSerializable("Person", person);
bundle.putSerializable("hashmap", (Serializable) hashmap);
fm = requireActivity().getSupportFragmentManager();
ft = fm.beginTransaction();
f = new FragmentFirst();
f.setArguments(bundle);
ft.replace(R.id.fragmentLayout, f, "main_fragment");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void refreshData() {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
Fragment currentFragment = fragmentManager.findFragmentByTag("main_fragment");
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(currentFragment != null) {
fragmentTransaction.detach(currentFragment);
fragmentTransaction.attach(currentFragment);
fragmentTransaction.commit();
}
}
}

As I see you are trying to go to a new instance of FragmentA in your booking activity. If you want to send data to an activity, process the data and return the result, in your case you could do it by starting new activity for result by startForActivityResult and also set the result before finish the activity with setResult method in your booking activity. In this case you can use the result via onActivityResult method. But I suggest you to use fragment for the booking process as well instead of activity.

Related

How can i show toolbar back button in fragments in android?

I am working on an android application where I have three fragments I want to show the back button on the toolbar of the fragments to go back to the previous fragments now how can I achieve that?? I am new to android please guide me.
public class SecondFragment extends Fragment {
Button button2;
private PageViewModel viewModel;
EditText editTextName, editTextEmail, editTextDesc;
public SecondFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_second, container, false);
button2 = view.findViewById(R.id.next2);
editTextName = view.findViewById(R.id.edittextName);
editTextEmail = view.findViewById(R.id.edditextEmail);
editTextDesc = view.findViewById(R.id.edittexDesc);
viewModel = new ViewModelProvider(requireActivity()).get(PageViewModel.class);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (editTextName.getText().toString().isEmpty() || editTextEmail.getText().toString().isEmpty() || editTextDesc.getText().toString().isEmpty())
{
editTextName.setError("Enter name");
editTextEmail.setError("Enter Email");
editTextDesc.setError("Enter Description");
}else {
// viewModel.setName(editTextName.getText().toString());
enterName(editTextName.getText().toString());
enterEmail(editTextEmail.getText().toString());
enterDesc(editTextDesc.getText().toString());
// viewModel.setEmail(editTextEmail.getText().toString());
// viewModel.setDescription(editTextDesc.getText().toString());
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
Fragment NAME = new LastFragment();
fragmentTransaction.replace(R.id.container, NAME);
fragmentTransaction.commit();
}
}
});
return view;
}
this is the code of my fragment borther i have three fragments like this i need to add the back button on the toolbar of there three fragemtns
You can add a toolbar to your activity, which is the container for these fragments.
Then in your fragments you can do something like this:
private void setupToolbar() {
YourActivity yourActivity = (YourActivity) getActivity()
if(yourActivity != null) {
yourActivity.toolbar.setSkipVisibility(View.GONE) // Or View.VISIBLE
yourActivity.toolbar.setText() // Set some text
yourActivity.toolbar.setOnBackButtonClickListener{ yourActivity.onBackPressed() }
}
}
Follow the steps down below.
fragmentTransaction.replace(R.id.container, NAME);
fragmentTransaction.addToBackStack(null); //Add this line
fragmentTransaction.commit();
This will solve your issue. Thank you.

Button inside fragment overlap with next fragment's button

The signup page of my app is divided into three fragments. FragmentA, FragmentB and FragmentC which is attached to same activity. On clicking the next button which is present in FragmentA it will call FragmentB and same is for FragmentB and FragmentC. As I move forward the buttons of the previous fragment overlaps the current one. Below is my code. How can I avoid this situation?
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_page);
init();
}
private void init() {
ViewPager2 viewPager = findViewById(R.id.signup_pager);
List<Fragment> fragmentList = new ArrayList<Fragment>();
FragmentA aFragment = new FragmentA();
FragmentB bFragment = new FragmentB();
fragmentList.add(aFragment);
fragmentList.add(bFragment);
SignupFragmentPagerAdapter signupFragmentPagerAdapter = new SignupFragmentPagerAdapter(this,fragmentList);
viewPager.setUserInputEnabled(false);
viewPager.setAdapter(signupFragmentPagerAdapter);
}
}
FragmentA.class
public class FragmentA extends Fragment {
EditText et_name;
Spinner sp_user_type;
Button bt_next;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fraga,container,false);
et_name = view.findViewById(R.id.editTextTextPersonName);
sp_user_type = view.findViewById(R.id.user_spinner);
bt_next = view.findViewById(R.id.button8);
bt_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentB bFragment = new FragmentB();
FragmentManager manager = getParentFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.frag_a, bFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
}
FragmentB.class
public class FragmentB extends Fragment {
Button bt_next;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragb,container,false);
bt_next = view.findViewById(R.id.button9);
bt_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentC cFragment = new FragmentC();
FragmentManager manager = getParentFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.frag_b, Fragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
}
Cause of your problem:
You are making fragment transaction (from A to B) within Fragment A itself; and not through the placeholder of these fragments (which is in your case the ViewPager itself; So the MainActivity still sees that the ViewPager is at the first page and therefore shows Fragment A in the background.
You have two options to solve this:
First: Since you're disable page scrolling; I don't see any use to
the ViewPager .. so you can just have a fragment placeholder in the
main activity, and make fragment transaction on this placeholder.
Second: if you have a need to the ViewPager, instead of making
fragment transaction, you can use
viewPager.setCurrentItem(position) and set the position to the
target fragment according to the order you add them in the adapter.
You can do that from your fragment when you hit the button using:
((MainActivity)requireActivity()).myViewPager.setCurrentItem(position)

How to load a new activity inside a fragment without losing the bottom navbar

As the title says when on the "Home Fragment" when i click on an image tile I want the new activity to load but I would like to keep the navbar visible. Currently with the code below the activity starts but the navbar disappears. I would like help to write code so the activity starts but the navbar stays.
public class HomeFragment extends Fragment {
private ImageView imageCbt;
private ImageView imageDistorted;
#Nullable
#Override
public android.view.View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
// get the button view
imageCbt = getView().findViewById(R.id.whatIsCbt);
imageDistorted = getView().findViewById(R.id.distortedThinking);
// set a onclick listener for when the button gets clicked
imageCbt.setOnClickListener(new View.OnClickListener() {
// Start new list activity
public void onClick(View v) {
Intent mainIntent = new Intent(getActivity(),
IntroActivity2.class);
startActivity(mainIntent);
}
});
imageDistorted.setOnClickListener(new View.OnClickListener() {
// Start new list activity
public void onClick(View v) {
Intent mainIntent = new Intent(getActivity(),
TwelveTypesDistortedThinkingActivity.class);
startActivity(mainIntent);
}
});
}
To change the current fragment, you can replace the code inside your click listeners to this one (Replacing a fragment with another fragment inside activity group):
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Then you need to convert your activities to Fragment (maybe some refactoring will be necessary) and to change the current fragment in the onClickListener methods.
PS: When you use a navbar, fragments are a best practice in application architecture.

Android Fragment Back press

I have a couple of fragments. But all the fragments lead to PeriodFragment when they press a button. My question is how do I implement so that when the user presses the BACK button on his mobile phone, the PeriodFragment will switch back to the fragment it was entered from.
This is the java code from PeriodFragment.java:
public class PeriodFragment extends Fragment {
Button btnPretrazi;
public PeriodFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_period, container, false);
//buttonPretraziPeriod
btnPretrazi = (Button) view.findViewById(R.id.buttonPretraziPeriod);
btnPretrazi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"test", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
This is my TvrdjavaFragment.java (one of the fragments that have the button to switch to PeriodFragment.java) :
package com.example.ivanp.msnis;
public class TvrdjavaFragment extends Fragment {
Button btnIdinaperiod;
public TvrdjavaFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tvrdjava, container, false);
// Inflate the layout for this fragment
//show date
TextView datumprikaz = (TextView) view.findViewById(R.id.datumprikaz);
Date danas = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String novDatum = sdf.format(danas);
datumprikaz.setText(novDatum);
//End of show date
btnIdinaperiod = (Button) view.findViewById(R.id.buttonIdinaperiod);
btnIdinaperiod.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PeriodFragment periodFragment = new PeriodFragment();
FragmentTransaction periodFragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
periodFragmentTransaction.replace(R.id.frame, periodFragment);
periodFragmentTransaction.commit();
}
});
return view;
}
}
I'm new to android studio, so please tell the details.
According to android docs When using fragments in your app, individual FragmentTransaction objects may represent context changes that should be added to the back stack. For example, if you are implementing a master/detail flow on a handset by swapping out fragments, you should ensure that pressing the Back button on a detail screen returns the user to the master screen. To do so, call addToBackStack() before you commit the transaction:
// Works with either the framework FragmentManager or the
// support package FragmentManager (getSupportFragmentManager).
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail")
// Add this transaction to the back stack
.addToBackStack()
.commit();
Adding to backstack will solve the problem:
periodFragmentTransaction.replace(R.id.frame, periodFragment);
periodFragmentTransaction.addToBackStack(null);
periodFragmentTransaction.commit();

Removing a fragment not working

I want to remove a fragment and show a toast when I click a textView. My code shows the toast, but doesn't remove the fragment.
My method:
public void hide(View view) {
My_frag myFrag= new My_frag();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.remove(myFrag);
transaction.commit();
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG)
.show();
}
My_frag class:
public class My_frag extends android.support.v4.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.my_frag_layout, container, false);
}
}
At some point you must create and add the Fragment correct? You are re-creating the fragment in your hide(...) method so you are trying to remove something that has never been added. Sure you may have added an instance, but not the instance you are trying to remove.
Instead, create a global variable Fragment fragToRemove in your Activity. When you create the fragment (that is where ever you do transaction.add(fragToRemove = new My_Frag);) you will hold an instance. then change your transaction.remove(myFrag) to transaction.remove(fragToRemove) and it should work just fine.
Take the instance of Fragment Transaction other than that was taken while adding fragment to activity and call remove method on that and pass the same instance of Fragment which was used at the time.
Example:
public class MainActivity extends AppCompatActivity {
FragmentTransaction fragmentTransaction;
BlankFragment blankFragment;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.activity_button);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
blankFragment=new BlankFragment(); //Fragment instance
fragmentTransaction.add(R.id.main_layout,blankFragment).commit();
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.remove(blankFragment).commit(); //created different
}
});
}
In the same way you can do in fragments also and can also remove fragment X on the click of component of fragment X.

Categories