How to change texts in Fragments? - android-fragments

I want to change texts in fragments, but I keep getting error like this
java.lang.NullPointerException: Attempt to read from field 'android.widget.TextView com.javahelp.databinding.FragmentHomeBinding.Aboutus' on a null object reference in method 'android.view.View com.javahelp.frontend.fragments.HomeFragment.onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)'
`
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_home, container, false);
binding.Aboutus.setText("Changed");
return v;
}
`
The one below is the mainpage where I am switching fragments
`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityFgBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
replaceFragment(new HomeFragment());
binding.bottomNavigationView.setOnItemSelectedListener(item ->{
switch(item.getItemId()){
case R.id.home:
replaceFragment(new HomeFragment());
break;
case R.id.account:
replaceFragment(new AccountFragment());
break;
case R.id.search:
replaceFragment(new SearchFragment());
break;
}
return true;
});
}
`
I was expecting the word "About Us" in home fragment would change to "Changed". I am trying to see if setText is working, but it is not. I looked for possible solutions, but they are not working.So I am not sure how to solve this. Appreciate some help and suggestions!

you can not set text in onCreateView method, put this line into onViewCreated method

Related

Change fragment activity through fragment directly from button Xamarin.Android

I'm using navigation drawer template from Xamarin and it working perfectly. So I can change layout dynamically. Now, I need to change fragment directly from single button (like shortcut). Changing between fragments works differently not like simple activity. In activity I can do simple code to change activity through a button:
Intent nextActivity = new Intent(this, typeof(ItemAddFormActivity));
StartActivity(nextActivity);
But, how to change fragment layout from single button? I'm still searching how to change fragment between fragment with button.
Maybe someone here can help me.
Thanks in advance.
This is how i have implemented in my solution, might help you
this is my fragment
public class Fragment3 : Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public static Fragment3 NewInstance()
{
var frag1 = new Fragment3 { Arguments = new Bundle() };
return frag1;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
return inflater.Inflate(Resource.Layout.fragment3, null);
}
}
To Display Fragment on button event use this
Android.Support.V4.App.Fragment fragment = null;
fragment = Fragment3.NewInstance();
if (fragment == null)
return;
SupportFragmentManager.BeginTransaction()
.Replace(Resource.Id.content_frame, fragment)
.Commit();

setOnItemSelectedListener seems to work only the first time the app is launched

I'm using a spinner in the menu of a fragment, load its data in the onCreateView. It works fine when the app is launched,however, the spinner disappears when the user navigates to a different fragment and comes back or when the app is opened the next time.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
setHasOptionsMenu(true);
getSpinnerValues(); //string request to add values to TrailList
}
#Override // ...
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.map_menu, menu);
super.onCreateOptionsMenu(menu, inflater); //temp
//setData();
final MenuItem item = menu.findItem(R.id.trailfiller);
mySpinner = (Spinner) MenuItemCompat.getActionView(item);
ArrayAdapter<Trail> adapter = new ArrayAdapter<Trail>(getContext(), android.R.layout.simple_spinner_dropdown_item, TrailList);
mySpinner.setAdapter(adapter);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Trail country = (Trail) parent.getSelectedItem();
Toast.makeText(getContext(), ""+country.getId()+""+country.getName(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
The moment it goes blank, the onItemSelected isn't getting triggered either.Strange thing to note is the spinner is consistent when the values are hardcoded. What am I missing here?
The onItemSelected would get triggered.Problem was with the ArrayList of size 0. Populating it inside the onCreateOptionsMenu will help. Alternatively,you can add an item to the list inside the onCreateOptionsMenu, which will help you get rid of this issue
Spinner spinner= new Spinner();
spinner.setName("select a country");
TrailList.add(spinner);

Android DialogFragment does not get dismissed on Button OnClickListener callback

I have a custom DialogFragment as an inner class in my Activity. The custom DialogFragment contains 2 Buttons.
The first Button opens the Camera and the second one opens the Gallery.
Normally this DialogFragment is shown after an Image is pressed.
Until here everything is fine.
Now I want add a new functionality. When the Activityis opened the first time, I want to open the Camera automatically, that means I want to "press" the first Button of my DialogFragment.
In my Activity onCreate method I just show the DialogFragment and perform a click on the first Button. The problem is that the DialogFragment is not dismissed.
Here is my code:
public static class MyDialogFragment extends DialogFragment {
Button openCameraButton;
Button openGalleryButton;
boolean openCameraAutomatically;
public static MyDialogFragment newInstance(boolean openCameraAutomatically) {
MyDialogFragment f = new MyDialogFragment();
Bundle args = new Bundle();
args.putBoolean("open_camera", openCameraAutomatically);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openCameraAutomatically = getArguments().getBoolean("open_camera");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.my_dialog, container, false);
getDialog().setTitle("title");
openCameraButton = (Button) rootView.findViewById(R.id.open_camera_button);
openCameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// launch Camera Intent...
getDialog().dismiss();
}
});
openGalleryButton = (Button) rootView.findViewById(R.id.open_gallery_button);
openGalleryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Launch Gallery Picker Intent
getDialog().dismiss();
}
});
if(openCameraAutomatically) {
openCameraButton.performClick();
}
return rootView;
}
}
And here is how I call it:
FragmentManager fm = getSupportFragmentManager();
MyDialogFragment myDialogFragment = MyDialogFragment.newInstance();
myDialogFragment.show(fm, "");
The line getDialog().dismiss(); does not dismiss the DialogFragment, after the Camera callback (onActivityResult) the DialogFragment is still visible. If I press the Button manually (without using the method performClick) everything works fine.
Any ideas?
Thanks.
Try just dismiss() to dismiss the dialog and the fragment instead of getDialog().dismiss() which just dismisses the dialog and but not the fragment.
https://developer.android.com/reference/android/app/DialogFragment.html#dismiss()
void dismiss ()
Dismiss the fragment and its dialog. If the fragment was added to the back stack, all back stack state up to and including this entry will be popped. Otherwise, a new transaction will be committed to remove the fragment.
Update:
Here is another thought. You are trying to dismiss the dialog before the view for the DialogFragment is fully ready. This isn't a problem once the buttons are available for you to push, i.e., the layout is complete.
Try moving the automatic dismissal later in life cycle. I think that will work for you.

Android - Reload a Fragment that is Part of ViewPager

I need help with reloading a Fragment that is part of a ViewPager. Here is my current setup:
ReportActivity extends FragmentActivity and uses ViewPager to host 4 Tabs
TAB 1 to 4. Each Tab is a Fragment with seperate layout.
ViewPager uses TabsPagerAdapter to switch between the tabs and this works as expected.
TAB1Fragment displays a graph using a static dataset. Now I have added a spinner to dynamically change the dataset and I am looking for ways to reload the Fragment so it can re-display the graph with the correct dataset. The following ints correspond to the values of the Spinner.
static final int REPORT_PERIOD_DAY = 0;
static final int REPORT_PERIOD_WEEK = 1;
static final int REPORT_PERIOD_MONTH = 2;
static final int REPORT_PERIOD_YEAR = 3;
I have a method that correctly calculates the correct data based on the the int passed in, what I am struggling with is how to create an Intent or any other method that will recreate TAB1Fragment and passes it an int parameter.
Here is where I want to re-create the Fragment
mReportPeriodSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
//How can I re-load the Fragment here?
reloadFragment(REPORT_PERIOD_DAY);
break;
case 1:
reloadFragment(REPORT_PERIOD_WEEK);
break;
case 2:
reloadFragment(REPORT_PERIOD_MONTH);
break;
case 3:
reloadFragment(REPORT_PERIOD_YEAR);
break;
}
}
Please can you give me an idea of how to write the code that goes into the method reloadFragment(Int period)
I would recommend re-configuring the existing fragment, rather than constructing a new fragment with the new report period.
I'm guessing that you currently configure your graph inside TAB1Fragment's onCreateView. If you move that configuration code to onResume, then you can call the same function when the user selects something in the spinner.
public class TAB1Fragment extends Fragment {
int reportPeriod;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = ...
reportPeriod = REPORT_PERIOD_DAY; // default report period
return rootView;
}
#Override
public void onResume() {
super.onResume();
configureGraph();
}
private void configureGraph() {
//TODO put all the code that draws your graphs here, using reportPeriod
}
public void reloadFragment(int reportPeriod) {
this.reportPeriod = reportPeriod;
configureGraph();
}
}
If this approach really doesn't work for you, and you really need a new fragment each time, then this question explains how to get the tag for a fragment so that you can tell the FragmentManager to replace it:
Replace Fragment inside a ViewPager

Update fragment from activity

I have a activity which have two fragments.
Activity receives broadcast events for the two fragments.
One fragment has a image button and text view. When the image button is clicked an event is send to the server and server responds back with live broadcast event.
We receive the response in activity and I need to update the UI of the fragment(the image button needs to be changed with another image)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.single_window_lock, container, false);
updateUI(view);
return view;
}
public void updateUI(View view){
String lockName;
final String lockState;
final boolean state;
final ImageButton singleLockImage = (ImageButton)view.findViewById(R.id.single_lock_image);
final TextView lockNameText = (TextView)view.findViewById(R.id.single_lock_name);
final TextView lockStateText = (TextView)view.findViewById(R.id.single_lock_state);
final ProgressBar progress = (ProgressBar)view.findViewById(R.id.singleLockProgress);
doorLock = LockState.getValue();
lockName = doorLock.getName();
if (doorLock.isLocked()) {
lockState = getActivity().getString(R.string.door_locks_locked);
singleLockImage.setImageResource(R.drawable.doorlocks_single_locked);
state = true;
} else {
lockState = getActivity().getString(R.string.door_locks_unlocked);
singleLockImage.setImageResource(R.drawable.doorlocks_single_unlocked);
state = false;
}
lockNameText.setText(lockName);
lockStateText.setText(lockState);
singleLockImage.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().changeState(state);
}
}
);
}
I thought to call updateUI, which will get the new state from the cache saved after the broadcast event received in Activity, but I am not sure how to pass (view)
Use FragmentActivity instead.
in FragmentActivity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
// Create an instance of ExampleFragment
TestFragment0 firstFragment = new TestFragment0();
// In case this activity was started with special instructions from an Intent,
// pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, firstFragment).commit();
}
in FragmentActivity for fragments :
TestFragment0 firstFragment0 = new TestFragment0();
firstFragment0.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,firstFragment0).commit();

Resources