Android - show fragment with custom text in view - java

I need to show several fragments on the screen. All fragments are instances of one fragment class, but I need to be able to set my values to view attrbutes on these fragments (text in TextView for example). I tried many solutions from here, but didn't find one.
What I'm doing now:
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction = manager.beginTransaction();
List<Comment> comments = place.getComments();
int i = 0;
for (Comment comment : comments) { //some cycle...
ReviewFragment reviewFragment = new ReviewFragment();
transaction.add(scrollView.getId(), reviewFragment, "review" + i);
((TextView) reviewFragment.getView().findViewById(R.id.author)).setText(comment.getAuthor());
i++;
}
transaction.commit();
But I get NullPointerException: reviewFragment.getView() is null. I tried to commit the transaction and begin new after each fragment, but it didn't helped. How can I set custom values in fragment views?
P.S. I didn't do something special in overriden methods in my ReviewFragment. Should I?
Thanks!

You can call the fragment's method setArguments() when you construct your fragment and pass the text you would like to display. Then inside the ReviewFragment class you can call getArguments() to retrieve the text and display it.
in the part that you are creating your fragment:
ReviewFragment reviewFragment = new ReviewFragment();
Bundle args = new Bundle();
args.putString("text", "The text to display here");
reviewFragment.setArguments(args);
transaction.add(scrollView.getId(), reviewFragment, "review" + i);
and in the onCreateView() of your ReviewFragment
// after inflating the view and before returning it
String textToDisplay = getArguments().getString("text");
myTextView.setText(textToDisplay);

Related

Adding a fragment to RecyclerView

I have an app with functionality to show one record or a list of them. I have a fragment for single record, so I decided for a list I want to fill a RecyclerView with cards, and add a fragment into each card. I am getting IllegalArgumentException: Cannot add a null child to a ViewGroup on a line in onBindViewHolder():
holder.frameLayout.addView(ResultFragment.newInstance(id).getView())
I'm not so sure how to work with a Recycled View and Fragments but if you use a linearLayout or RelativeLayout, you can use FragmentManager in the onCreateView method or generate you're pwn method to change the content in the view (fragment) that you want to change:
FragmentManager fm = getSupportFragmentManager();
transaction = fm.beginTransaction();
oneFragment = new OneFragment();
transaction.replace(R.id.fragmentContent, oneFragment);
transaction.commit();
the R.id.fragmentManager are a <fragment> section in your view
Regards

How to change dynamically inflated textview from after proceeding an action on other fragment?

So, what my problem is that in one fragment(w/i a viewpager, I'll call this Fragment A) I click on this dynamically created button that adds a new fragment(I'll call this Fragment B) in a framelayout which allows me to use PayPal service. On PayPal Activity result, Fragment B communicates with the main Activity via a communicator(an interface class) to call Fragment A to change that text. But I'm getting a null pointer exeception crash.
To be specific:
what I did was that I made a global TextView variable that is initialized on click. I did this b/c I have a list of other things that are dynamically inflated and to avoid the TextView from being initialized with wrong layout I initialized it on click.
bidChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
eventListChangeKey = keyVal;
eventListChangeIdx = eventListIdx;
eventBiddingChangeIdx = finalI;
priceToChage = (TextView) biddersLayout.findViewById(R.id.single_list_bidder_bid_price);
Bundle bundle = new Bundle();
bundle.putInt("auctionID", auctionId);
bundle.putInt("dateID", dateId);
bundle.putInt("FromWhere", 2);
Fragment fragment = new Fragment_Home_ItemInfo_Bid();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.container_mainScreen, fragment, "itemInfo_bid")
.addToBackStack(null)
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
});
In the main activity
public void changeBidderPrice(String s) {
Fragment fragment = viewPagerAdapter.getItem(1);
((Fragment_List) fragment).changePrice(s);
}
is what I do
back in Fragment A
public void changePrice(String val) {
priceToChage.setText(val);
dataMap.get(eventListChangeKey).get(eventListChangeIdx).getBidList().get(eventBiddingChangeIdx).setPrice(val);
}
I've thought this over an over but I just can't figure this out. I've searched for similar cases in StackOverflow but I wasn't able to get a help.
Would the problem be the way I initialize that TextView? or is it the way I'm calling Fragment A from the main activity?
for fragments onViewCreated() is called after onCreateView() and ensures that the fragment's root view is non-null. Any view setup should happen here. E.g., view lookups, attaching listeners.
source : codepath
for activities onCreate()

Completely Refresh Fragment

I have a fragment and I need to completely refresh/reinstantiate it.
By refreshing I mean recreating fragment.
I have tried using FragmentManager with detach() method but it didn't help. All EditText children of that fragment still have their values entered even though the fragment was refreshed
Is there any way to achieve this result?
if there are only edit texts , create a method that sets all edit texts to empty string that is et(edit_text object),
et.setText(""); //edit text will be reset
Put the following code inside the fragment which need to be refreshed.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit();
Use fragment manger according to your code (if it is an old version then this will be supportFragmentManager)
Put and call this method to your fragment
private void reloadFragment(){
Fragment frg = getActivity().getSupportFragmentManager().findFragmentByTag(ReceiptFragment.TAG);
final FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}

Failure to get fragment address from MainActivity when trying to update an edit text field

I have a MainActivity (MA) running several fragments, which do not talk to each other but communicate to the MA via the 'onClick' android mechanism.
Driven by a spinner choice and an 'onClick' button press, we arrive in the RetrievePatientRecord method of the MA.
I carry out a database call to get the chosen db record (as per the commented line) and then test to see if there is an existingPatient fragment present into which I intend to put the database record's various fields as its essentially a form.
With a not found, 'null' condition, I instantiate a new instance of a ExistingPatientFg fragment.
However when I attempt to use the existingPatient reference via a setter in the ExistPatientFg fragment to set the 'Title' field value the program falls over with a NPE !
I have tried to 'get the fragment address' using commented out line … getFragmentManager().findFragmentById(R.id….) but interestingly using android studio's code completion facility the only R.id. object it will offer is the 'fragment_container' which though it compiles, it falls over on this line of code if I leave it in.
So I'm a bit stumped. I've read through most of the other S/O answers in this fragment/MainActivity/edit text field, subject area but haven't been able to get a solution which can help me, so I'm after some assistance here. (also it may be relevant that my activity_main.xml layout file is using a FrameLayout layout with its id as 'fragment_container')
public void RetrievePatientRecord(View view) {
// do database query to get record before displaying in patient record fragment
this.patientID = findPatientRecordFg.patientID;
Log.d(DEBUGTAG, " ---->>>>> retrieve this record L 404 with ID = " + findPatientRecordFg.patientID);
// db query for existing patient's records
findPatientRecordFg.db.getPatientRecords(patientID);
// populate patientdetails fragment fields and re display patientdetails fragment.
if (existingPatient != null) {
populatePatientDetails_fgWithCurrentValues();
trans = getFragmentManager().beginTransaction();
trans.replace(R.id.fragment_container, existingPatient);
trans.addToBackStack(null);
trans.commit();
}else
if (existingPatient == null){
existingPatient = new ExistingPatientFg();
// ExistingPatientFg existingPatient = (ExistingPatientFg)getFragmentManager().findFragmentById(R.id.fragment_container);
cTitle = findPatientRecordFg.db.geteTitle();
Log.d(DEBUGTAG, " ######## -->>>>> reached just before setTitleField L 424 with value Title = "+ cTitle);
existingPatient.setTitleField(cTitle);
//populatePatientDetails_fgWithCurrentValues();
trans = getFragmentManager().beginTransaction();
trans.replace(R.id.fragment_container, existingPatient);
trans.addToBackStack(null);
trans.commit();
}
}
the fragment's java code is :-
public class ExistingPatientFg extends Fragment {
public ButtonPlus btn;
public ButtonPlus analysisBtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.patientdetails_fg, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
EditText editText = (EditText)getView().findViewById(R.id.bannerText);
editText.setText("Existing Patient");
btn = (ButtonPlus)getActivity().findViewById(R.id.Goto_Scanning_Page);
analysisBtn = (ButtonPlus)getView().findViewById(R.id.Analysis);
btn.setEnabled(true);
}
public void setTitleField(String string){
EditText et = (EditText)getView().findViewById(R.id.Title);
et.setText(string);
}
I suspect that the null pointer exception is not that you don't have a reference to the fragment, but that you are calling setTitleField before the fragment view has been inflated so the edit text field doesn't exist yet.
Try moving setTitleField to after the trans.commit or better yet pass the title to the fragment as an extra argument.
existingPatient = new ExistingPatientFg();
Bundle bundle = new Bundle();
bundle.putString("title",cTitle);
existingPatient.setArguments(bundle);
trans = getFragmentManager().beginTransaction();
trans.replace(R.id.fragment_container, existingPatient);
trans.addToBackStack(null);
trans.commit();
And use the following inthe Fragment's onCreateView to get the title
String cTitle = getArguments().getString("title");
See How to pass a variable from Activity to Fragment, and pass it back?
You can either find the fragment by tag that you supply when adding the fragment:
getFragmentManager().beginTransaction().replace(R.id.fragment_container, existingPatient, "Your Tag Here");
and than find it by tag:
getFragmentManager().findFragmentByTag("Your Tag Here")
Or, if you still want to find by ID - it should be the one that is returned by:
fragment.getID();
it should be either the container of the fragment or the top layout in the fragment I'm not sure. (So you can check for debugging after adding the fragment
if fragment.getID()==R.id.container

Calling Fragment Method from Activity in Swipeable Tab Views

I've been working on a project that has swipeable views with tabs.
The tabs exist as fragments. I want to run a fragment method from the main activity on a periodic basis.
To run the methos, I dont' have the ID for the fragment. I read in other posts that:
String tag = "android:switcher:" + TabActivity.this.viewPager.getId() + ":" + "0";
Tab1Fragment fragment = (Tab1Fragment) getSupportFragmentManager().findFragmentByTag(tag);
fragment.someMethod();
will return the fragment I desire, which happens to be the zero-th or first tab. However, running this code returns a nullpointer exception.
Any help will be appreciated. Thanks :)
In your code, at some point you must have:
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.framelayout, new SomeXYZFragment(), "some_xyz_fragment");
ft.commit();
Add the line:
fm.executePendingTransactions();
after the line ft.commit();
Try this. It should work.

Categories