commit fragment from onLoadFinished within activity - android-fragments

I have an activity which loads a data list from the server using loader callbacks. I have to list out the data into a fragment which extends
SherlockListFragment
i tried to commit the fragment using
Fragment newFragment = CategoryFragment.newInstance(mStackLevel,categoryList);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
in onLoadFinished and it gives an IllegalStateException saying
java.lang.IllegalStateException: Can not perform this action inside of onLoadFinished
I have referred the example in actionbar sherlock, but those examples have loaders within the fragments and not the activity.
Can anybody help me with this o that I can fix it without calling the loader from the fragment!

Atlast, I have found a solution to this problem. Create a handle setting an empty message and call that handler onLoadFinished(). The code is similar to this.
#Override
public void onLoadFinished(Loader<List<Station>> arg0, List<Station> arg1) {
// do other actions
handler.sendEmptyMessage(2);
}
In the handler,
private Handler handler = new Handler() { // handler for commiting fragment after data is loaded
#Override
public void handleMessage(Message msg) {
if(msg.what == 2) {
Log.d(TAG, "onload finished : handler called. setting the fragment.");
// commit the fragment
}
}
};
The number of fragments depend on the requirement.
This method can be mainly used in case of stackFragments, where all fragments have different related functions.

As per the Android docs on the onLoadFinished() method:
Note that normally an application is not allowed to commit fragment transactions while in this call, since it can happen after an activity's state is saved. See FragmentManager.openTransaction() for further discussion on this.
https://developer.android.com/reference/android/app/LoaderManager.LoaderCallbacks.html#onLoadFinished(android.content.Loader, D)
(Note: copy/paste that link into your browser... StackOverflow is not handling it well..)
So you simply should never load a fragment in that state. If you really don't want to put the Loader in the Fragment, then you need to initialize the fragment in your onCreate() method of the Activity, and then when onLoadFinished occurs, simply call a method on your fragment.
Some rough pseudo code follows:
public class DummyFragment {
public void setData(Object someObject) {
//do stuff
}
public class DummyActivity extends LoaderCallbacks<Object> {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fragment newFragment = DummyFragment.newInstance();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
getSupportLoaderManager.initLoader(0, null, this)
}
// put your other LoaderCallbacks here... onCreateLoader() and onLoaderReset()
public void onLoadFinished(Loader<Object> loader, Object result) {
Fragment f = getSupportLoaderManager.findFragmentById(R.id.simple_fragment);
f.setData(result);
}
Obviously, you'd want to use the right object.. and the right loader, and probably define a useful setData() method to update your fragment. But hopefully this will point you in the right direction.

As #kwazi answered this is a bad user experience to call FragmentTransition.commit() from onLoadFinished(). I have found a solution for this event by using ProgressDialog.
First created ProgressDialog.setOnDismissListener(new listener) for watching the onLoadFinished().
Further i do progressDialog.show() before getLoaderManager().restartLoader().
And eventually place progressDialog.dismiss() in onLoadFinished().
Such approach allow do not bind main UI thread and Loader's thread.
public class FrPersonsListAnswer extends Fragment
implements
LoaderCallbacks<Cursor>{
private ProgressDialog progressDialog;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_persons_list, container, false);
//prepare progress Dialog
progressDialog = new ProgressDialog(curActivity);
progressDialog.setMessage("Wait...");
progressDialog.setIndeterminate(true);
progressDialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
//make FragmentTransaction.commit() here;
//but it's recommended to pass control to your Activity
//via an Interface and manage fragments there.
}
});
lv = (ListView) view.findViewById(R.id.lv_out1);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
final int position, long id) {
//START PROGRESS DIALOG HERE
progressDialog.show();
Cursor c = (Cursor) parent.getAdapter().getItem(position);
// create Loader
getLoaderManager().restartLoader(1, null, curFragment);
}
});
return view;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case 1:
//dismiss dialog and call progressDialog.onDismiss() listener
progressDialog.dismiss();
break;
default:
break;
}
}

Related

Start a fragment from MainActivity that calls another fragment. The listener returns to the MainActivity

My MainActivity(1) implements FragmentStatePagerAdapter, with SectionPagerAdapter and ViewPager. It works OK, apart from the problem I have to call getItemPosition to update one of the Fragments, which causes the whole thing to be recreated. Anyway...
One of the "tabs", calls a Fragment(2=BaixarOrcamentoFragment.java), which in turn, calls another Fragment(3=FillReasonToBaixaFragment.java), so the user can insert a text.
Fragment(2) implements THE LISTENER that Fragment(3) uses to return a "text value", so Fragment(2) can continue and finish it's tasks.
Here is the code in Fragment(2), that calls Fragment(3):
FragmentManager fragmentManager = getFragmentManager();
FillReasonToBaixaFragment fillFragment = new
FillReasonToBaixaFragment();
Bundle args = new Bundle();
args.putInt("ORCID", baixarModelList.get(masterPosition)
.getOrcGroupID());
fillFragment.setArguments(args);
fillFragment.show(fragmentManager, FILL_REASON_TO_BAIXA);
Then, Fragment(3) gets the bundle ORCID,stars the listener, get some data, shows a text input, and finishes by sending this "text" to the interface:
BaixaItemdoOrcamentoListener listener = (BaixaItemdoOrcamentoListener) this
.getContext();
..and then returning what has collected (text) using this interface (listener):
public interface BaixaItemdoOrcamentoListener
{
void OnFinishedFillReason(String mEditext);
}
However, it's not returning back to Fragment(2), which called Fragment(3), where I implemented the method to receive this returning value:
#Override
public void OnFinishedFillReason(String mEditext)
{}
It shows a cast error, saying that .MainActivity cannot be cast to .FillReasonToBaixaFragment$BaixaItemdoOrcamentoListener
I went on and DECLARED the OnFinishedFillReason inside the MainActivity, which implements FillReasonToBaixaFragment.BaixaItemdoOrcamentoListener.
Be aware now, that the actual implementation of the tasks are in Fragment(2).
Guess what: when I enter the text in Fragment(3) and press ( android:imeOptions="actionDone"), it returns to the MainActivity, NOT to the Fragment(2), the one that has called Fragment(3).
MainActivity doesn't know the existence of any of the the Views inside Fragment(2), a priori, which will, in turn, update all these views ONCE received the "text" from Fragment(3).
Perhaps I didn't search thoroughly, but I couldn't find anything that resembles this situation.
How can I make it happen?
Afternoon everyone.
I figured it out how to make this happen.
First: I removed OnFinishedFillReason interface from Fragment(2), and therefore, from Fragment(3).
In Fragment(2), I started the Fragment(3) like this, setting a setTargetFragment:
FragmentManager fragmentManager = getFragmentManager();
FillReasonToBaixaFragment fillFragment = new
FillReasonToBaixaFragment();
fillFragment.setTargetFragment(BaixaOrcamentoFragment.this,
FILL_REASON_TO_BAIXA);
Bundle args = new Bundle();
args.putInt("ORCID", baixarModelList.get(masterPosition)
.getOrcGroupID());
fillFragment.setArguments(args);
fillFragment.show(fragmentManager,
this.getClass().getSimpleName());
The target fragment is the Fragment(2) itself.
Then I added in Fragment(2):
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == FILL_REASON_TO_BAIXA && resultCode == Activity.RESULT_OK)
{// code in here }
In Fragment(3), I added in the onCreate(Bundle savedInstanceState) method, the following:
targetFragment = getTargetFragment();
if (targetFragment instanceof BaixaOrcamentoFragment)
{
orcID = getArguments().getInt("ORCID");
}
At the end of the returning elements, like this:
Intent returnData = new Intent();
Bundle bundle = new Bundle();
bundle.putString("EDITTEXT", txtEdited);
returnData.putExtras(bundle);
targetFragment.onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, returnData);
this.dismiss();
return true;
And then, inside the onActivityResult I collected the data, like this:
Bundle returnedValues = data.getExtras();
String mRazao = returnedValues.getString("EDITTEXT").trim();
And that was it.
But I still have a problem: I have 6 tabs. Tab 4 is never selected as currentItem, inside the method below:
#Override
public void onPageSelected(int position)
{
mViewPager.setCurrentItem(position);
}

Issue with ViewPager and FragmentStatePagerAdapter when activity is destroyed

I have an activity which creates viewpager adapter (FragmentStatePagerAdapter) and sets the viewpager to this adapter.
This is how viewpager adapter is created and is set to the viewpager widget.
viewPageAdapter = new viewPageAdapter(getSupportFragmentManager(), getApplicationContext());
mCustomSwipeViewPager.setAdapter(viewPageAdapter);
And this is how i am creating viewPageAdapter
public class viewPagerAdapter extends FragmentStatePagerAdapter {
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public viewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// returning newly created fragment
}
#Override
public int getCount() {
// returning total count
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
// This is where i am putting created fragment in the sparse array,
// which i will be accessing in the activity based on position
// for updating fragment views.
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// And here i am removing it from the sparse array
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
}
Now, i went to the developers options and checked "Donot keep activities".
This is where the problem starts, after moving forward this activity, this activity will get destroyed, which is fine.
Now if i come back, the a new adapter is created in onCreate() and is set to the viewpager, but it's not calling getItem() again, instead it's calling instantiateItem(), with fragment in memory as null.
I checked the fragmentmanager in debug mode, the fragment manager holds two fragments as activestate, with all fragment fields as null.
Things i have tried...
Tried clearing the fragment manager in onDestroy() of activity using
fragmentManager.getFragments.clear() but no luck.
Made getItemCount() of adapter to 0 and called notifydatasetChanged() on adapter in onDestroy(), still getting the same.
However, if comment out the super.onSavedInstance() of activity, it's working fine, but this is not i want as it's failing for few cases.
Is there any way wherein if i create a new adapter and again set it to the viewpager, it should start afresh, i.e should call getItem() from first position without minimizing the performance of fragmentStateViewPagerAdapter.
Any kind of help or suggestion would be appreciated.
The only solution i figured out is to comment out the default super.onSaveInstanceState(outState) inside onSaveInstanceState(Bundle outState) callback of activity lifecycle.
#Override
protected void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState);
}
Doing so will not keep the fragment old instance in the fragmentManager of viewpager and will start afresh.
I couldn't thought of any better solution, as there are many global variables inside fragment and in also in activity and it's presenter, and saving them in the onSaveInstanceState bundle and them restoring them in onCreate or in onRestoreInstanceState() would be very heavy for me.
Any better solution or approach than this is still appreciable.
Had the same issue, was assigning the fragment's view container an id programmatically, we removed this and assigned an id in its layout XML file and the issue went away.

JavaFX - Call "updateMessage" for TextArea from background Task - Two problems found

I am having two problems when trying to use "updateMessage" in a JavaFX task.
Issue #1
seems to be a known behavior, but I am not yet sure how exactly I can workaround it.This one is not (yet) critical to me.
The problem is that not all the updates I am performing in a background Task are displayed in the UI (at least the UI does not hang/freezes anymore, which was my initial issue).
My Code of the UI part:
TextArea console = new TextArea();
Button button01 = new Button("Start");
button01.setOnAction(new EventHandler() {
#Override
public void handle(Event event) {
if (ms.getState() == State.READY) {
ms.messageProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable,
String oldValue, String newValue) {
console.appendText(newValue+"\n");
}
});
ms.start();
}
}
});
My Service:
public class MyService extends Service<Object> {
#Override
protected Task createTask() {
//here we use "MyTask" first to show problem #1
MyTask ct = new MyTask();
//here we use "MyTask2" first to show problem #2
// MyTask2 ct = new MyTask2();
try {
ct.call();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("MyService end");
return ct;
}
}
My Task (#1)
public class MyTask extends Task<Object> {
#Override
public EventHandler<WorkerStateEvent> call() {
System.out.println("call() is called");
if (Thread.currentThread().getName().equals("JavaFX Application Thread")){//yes, this might not be right, but if I do not do this, my stuff is executed twice because "call()" is called twice, but the textarea area is just updated in the second run (the non javafx application thread).
return null;
} else{
//actually here I want to do some 'heavy' stuff in the background
//and many things of this heavy stuff should be displayed / logged within the UI
//but very likely (hopefully) new messages (updateMessage) will not be send as fast as in the following loop
for (int i=0;i<10000000;i++){
updateMessage("This is update number'"+i+"' from the background thread");
}
Platform.runLater(new Runnable() {
#Override
public void run() {
try{
//here is the chance to get back to the view
}finally{
}
}
});
return null;
}
}
This basically works, but not every single loop is displayed in the UI.
How do I (correctly) make sure every loop is displayed?
Screenshot: Messages are displayed but not for every loop
Issue #2
Currently blocks my attempt to bring my little text-based game into a JavaFX application.
The main problem is that I am able to call "updateMessage" from the Task directly (see above), but not from a another (sub-)class which I would need to bring all message updates from my game (each message describes the progress of the game) to the UI.
The Task I use (Task #2):
public class MyTask2 extends Task<Object> {
#Override
public EventHandler<WorkerStateEvent> call() {
// ...
UITools myTools = new UITools();
myTools.logToUITest("Just one simple message");
// ...
Platform.runLater(new Runnable() {
#Override
public void run() {
try{
//here is the chance to get back to the view
}finally{
}
}
});
return null;
}
and the (sub-)class that I want to use to do the updateMessage (actually in my little game there would be even more classes that are called during the game and almost all of them trigger an update/message).
public class UITools {
public void logToUITest(String message){
updateMessage(message);
//how to allow 'updateMessage' from the Task to be executed from here?
}
This already results in "The method updateMessage(String) is undefined...".
How could I make it possible to call the updateMessage outside of the Task itself?
updateMessage() can only be called from within the call() method of a Task. It's a constraint imposed by the design of the Task class.
The missed message updates are due to the fact that there are too many updates and not all of them are forwarded to the event queue. Try to reduce the number of updates or sleep for a little while to separate them out in time

how to invoke fragmentB method in another fragmentA

I have a fragment_A with tabs, consider tabs as fragment_B and C. And am implementing custom keypad with "Done" key in it. In my main Activity iam calling the listener to press the done button
// Used when "Done" button pressed in keyboard
#Override
public void keylisten() {
((Housing) fragmentStack.lastElement()).whenokkeypressed();
}
Now i want to call a method from fragment_B which goes into the whenokkeypressed() of the fragment_A;
There are 2 things you should do
Make whenonkeypressed() static and call it from class name of the fragment like Fragment_A.whenonkeypressed()
(optional) instead of using keylisten of done in mainActivity you should prefer an anonymous inner class like
editText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
whenonkeypressed();
} });

How to Post a runnable to a View that invalidates the View sometimes doesn't work

I been fighting an odd issue these last few days. I have a custom ExpandableListAdapter where each row contains an ImageView, among other things. I have a class that handles the asynchronous loading of images from the multitude of places they may reside (disk cache, app data, remote server, etc). In my adapter's getView method I delegate the responsibility of returning a View to the list Item itself (I have multiple row types for my group list). I request the image load as follows:
final ImageView thumb = holder.thumb;
holder.token = mFetcher.fetchThumb(mImage.id, new BitmapFetcher.Callback() {
#Override
public void onBitmap(final Bitmap b) {
thumb.post(new Runnable() {
#Override
public void run() {
thumb.setImageBitmap(b);
}
});
}
#Override
public void onFailure() {
}
});

Resources