How to reload fragment when button clicked - java

I want to refresh fragment by clicking retry button in onCreateView.
If my internet is disconnected it must return fragment_no_internet_error layout. There is a button to reload fragment.
It gives me the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: ir.hamedanmelk.hamedanmelk, PID: 21310
java.lang.NullPointerException: Attempt to read from field 'androidx.fragment.app.FragmentManager androidx.fragment.app.Fragment.mFragmentManager' on a null object reference
at androidx.fragment.app.BackStackRecord.detach(BackStackRecord.java:220)
my OnCreateView:
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v;
CheckConnectivity checkConnectivity=new CheckConnectivity();
if(!checkConnectivity.isNetworkAvailable(getActivity())) {
v=inflater.inflate(R.layout.fragment_no_internet_error, container, false);
Button retrybutton = (Button)v.findViewById(R.id.no_internet_fragment_button_retry);
retrybutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment frg = getActivity().getSupportFragmentManager().findFragmentById(R.id.HelpFragment);
final FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
});
return v;
}
v=inflater.inflate(R.layout.fragment_f_a_q, container, false);
mwebview = (WebView) v.findViewById(R.id.webview_f_a_q);
WebSettings webSettings=mwebview.getSettings();
webSettings.setJavaScriptEnabled(true);
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
//TODO Change FontFace https://stackoverflow.com/questions/3900658/how-to-change-font-face-of-webview-in-android
mwebview.setWebViewClient(new WebViewClient(){
return v;
}
}

Try to use this code. Becuase I think the issue is with API level
FragmentTransaction transaction = mActivity.getFragmentManager()
.beginTransaction();
if (Build.VERSION.SDK_INT >= 26) {
transaction.setReorderingAllowed(false);
}
transaction.detach(this).attach
(this).commit();

try this.
in your fragment
((MainActivity)getActivity()).reload()
in your MainActivity
void reload(){
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// R.id.fragment_layout is your fragment container view
ft.replace(R.id.fragment_layout, instanceFragment);
ft.commit()
}

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)

Calling a button in Fragment view from Activity

I want to reach fragment item in Activity method but i get a null pointer error.
Fragment Class
Button button;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment, container, false);
button= view.findViewById(R.id.button);
return view;
}
public Button getButton(){
return button;
}
MainActivity
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = (Fragment)fm.findFragmentById(R.id.Framelayout);
fragment.getButton().setText("Test");
LOGCAT
java.lang.NullPointerException: Attempt to invoke virtual method
'android.widget.Button com.example.android.fragment.Fragment.getButton()'
on a null object reference
at
com.example.android.MainActivity$1$1.onDataChange(MainActivity.java:141)
For adding the fragment
private void addFragment(FragmentManager manager)
{
YOURFRAGMENT fragment= new YOURFRAGMENT();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(CONTAINER-ID,fragment,YOURFRAGMENT.class.getSimpleName()).commitNow();
}
for getting the fragment
private void getFragment(FragmentManager manager,String TAG){
YOURFRAGMENT fragment= (YOURFRAGMENT) manager.findFragmentByTag(TAG);
if(fragment!=null){
//access button here
}
}
to get yours
getFragment(fragmentManager, YOURFRAGMENT.class.getSimpleName())k
Add the Fragment using TAG
String TAG="YourTAG";
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, mFragment, TAG)
.commit();
You can invoke a method from your activity like this
Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG);
if (fragment instanceof YourFragmentClass ) {
fragment.getButton().setText("Test");
}
Hope it helps you.
try with getFragmentManager() instead of getSupportFragmentManager()

how can i access the button id in activity from fragment

How to access button id in an activity.
Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_meter);
if (Build.VERSION.SDK_INT >= 23) {
checkLocationPermission();
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment map = new Map();
fragmentTransaction.add(R.id.fragment_container, map);
fragmentTransaction.commit();
...
}
Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_map, container, false);
Button button = (Button)getActivity().findViewById(R.id.btnStop);
}
How to implement setOnClickListener method of btnStop in my code fragment?
add this to fragment:
final View.OnClickListener btnClick = new View.OnClickListener() {
public void onClick(View v){
//button clicked
}
}
add this to activity onCreate:
Button button = (Button)getActivity().findViewById(R.id.btnStop);
button.setOnClickListener(map.btnClick );
another way:
add this to fragment:
Button btnStop;
add this to onCreate of Activity:
map.btnStop = (Button)getActivity().findViewById(R.id.btnStop);
Then in any event listener of fragment that is called after onCreate of Activity (for example onActivityCreated and onStart) you have access to the btnStop and you can set onClick listener for it.
You can create a method in the activity, probably like
public void yourMethod() {
button.performClick();// you can access all the components present in your activity
}
Now create an instance of the activity in the fragment and access this method.
YourActivity activityInstance = (YourActivity) getActivity();
And then you can access the method using the isntance of the activity like
activityInstance.yourMethod();
Whenever you want to perform a click function, you just have to call the funciton.

Fragment Back Navigation Exiting to Home Screen - Android

I have one fragment in an activity, I can launch the fragment using FragmentManager and FragmentTransaction, but when I try to navigate back to the Activity via the back button, the app exits.
Here is my fragment creation & transaction in the Activity class:
DetailFragment df = new DetailFragment();
try {
df.initFragment(jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, df);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
I also override onBackPressed()
#Override
public void onBackPressed() {
super.onBackPressed();
}
With the above setup, one press of the back button exits to the home screen.
I also tried to modify onBackPressed() to do:
#Override
public void onBackPressed(){
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} else {
super.onBackPressed();
}
}
On this second version of onBackPressed(), it takes 2 back presses to go back to the home screen. Keep in mind I am trying to return to the original Activity.
Any suggestions?
P.S. I can add my fragment code if needed
Your second version of onBackPressed() requires 2 back presses to go back to the home screen. So it seems like fm.popBackStack() is getting called. Try replacing it with popBackStackImmediate().
Edit:
When you are creating the fragment, try using the following instead of .replace:
fragmentTransaction.add(R.id.fragment_container, df);
If that still doesn't work, try:
#Override
public void onBackPressed(){
FragmentManager fm = getFragmentManager();
if (df.isVisible) {
fm.beginTransaction().remove(df).commit();
} else {
super.onBackPressed();
}
}
(although this is less desirable as you are hard-coding what to remove).
The navigation was working, but in my Fragment's onCreateView I used setContentView() to the fragment view which painted the fragment view to the main activity, so it appeared that the back button would exit out if it was pressed twice, but it was actually returning to the main activity as it should, it just repainted the main activity so it wasnt possible to tell.
Thanks for the help #RogueBaneling !!
original code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_detail, container, false);
fragmentView.setClickable(true);
getActivity().setContentView(R.layout.fragment_detail);
final TextView movieTitleText = (TextView) getActivity().findViewById(R.id.movie_title_text);
movieTitleText.setText(title);
// editing textView code...
return fragmentView;
}
into:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_detail, container, false);
fragmentView.setClickable(true);
final TextView movieTitleText = (TextView) fragmentView.findViewById(R.id.movie_title_text);
movieTitleText.setText(title);
// editing textView code...
return fragmentView;
}

Categories