ViewPager Activity to notify a Fragment of a specific event - android

I have a ViewPager and it is using a FragmentAdapter in order to display several fragments of the same kind. Although these Fragments are basically instantiated from the same class, they are using a ListView to display different information. (Obviously the ListView is being poulated by an ArrayAdapter.)
A background service is also running and is constantly receiving data from the Internet. I want to be able to update a specific Fragment in the ViewPager when my background service has notified me of a specific event.
How can I do that?
A code snippet would be hugely appreciated!
(By the way, I have saw this similar question but I have no idea how to use their suggestion!)
To make it all more simple:
My activity with the ViewPager:
[Fragment 0] [Fragment 1] [Fragment 2]
The background service tells me (via a broadcast) to update the ListView in Fragment 1.
EDIT:
Here are sample codes:
public class ChatWindowPager extends FragmentActivity
{
private ViewPager mViewPager = null;
private ChatFragmentAdapter mAdapter = null;
#Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_window_pager);
this.mViewPager = (ViewPager) findViewById(R.id.chatPager);
this.mAdapter = new ChatFragmentAdapter(getSupportFragmentManager());
this.mViewPager.setAdapter(this.mAdapter);
.
.
.
}
class ChatFragmentAdapter extends FragmentPagerAdapter implements ViewProvider
{
public ChatFragmentAdapter(final FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(final int arg0)
{
String friendId = ..... // Some initializations
ChatWindowFragment f = ChatWindowFragment.newInstance(friendId);
return f;
}
#Override
public int getCount()
{
...
}
#Override
public View getView(final int position)
{
View v = getLayoutInflater().inflate(R.layout.tab_holder, null);
.
.
.
return v;
}
}
}
Now the fragments is defined like this:
public class ChatWindowFragment extends Fragment
{
public String friendId;
private ListView lv;
public static ChatWindowFragment newInstance(final String friendId)
{
ChatWindowFragment chatWindowFragment = new ChatWindowFragment();
Bundle bundle = new Bundle();
bundle.putString("friendId", friendId);
chatWindowFragment.setArguments(bundle);
return chatWindowFragment;
}
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.friendId = getArguments().getString("friendId");
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.chat_window, container, false);
this.friendId = getArguments().getString("friendId");
.
.
.
return v;
}
//The rest of the class
}
As I am using a FragmentPagerAdapter I don't see how I can set the tag of each fragment!
(Obviously, I am not using transactions to add the Fragments!)
EDIT 2:
I would like to know whether what I'm doing, is the correct way to handle what I want to do... Any other solution is also welcome!

Try this,
Register a broadcast receiver in all your fragments... like this
create a class which extends a broadcast receiver in all the classes, for eg:
public class FragmentReceiver1 extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}
}
and register this receiver in you fragment's onCreate ...
for eg. getActivity().registerReceiver(new FragmentReceiver1(), new IntentFilter("fragmentupdater"));
Now assign a unique id to each of you fragment like 1 for Fragment1, 2 for Fragment2 and likewise
now whenever you want to pass any data and update any of the fragment just send a broadcast with the data in intent and "fragmentupdater" as the intent-filter...
For eg:
Intent data = new Intent("fragmentupdater");
data.putString("key","data");
data.putInt("fragmentno",1); // Pass the unique id of fragment we talked abt earlier
activity.sendBroadcast(data);
Now each of your fragment will receive the data but you can verify if the data if for the same fragment by the unique id we passed in it in the onReceive function..., the intent which you get, is the intent we passed above

Have you tried FragmentManager.findFragmentByTag()
FragmentManager manager = getSupportedFragmentManager();
//with support package, else
//FragmentManager manager = getFragmentManager()
Fragment fragment = manager.findFragmentByTag("Tag You Created the Fragment");
if (fragment instanceof Fragment1){
Fragment1 fr = (Fragment1)fragment
fr.updateData(DATA)
//or any method of your choice
}
EDIT: I read carefully! The instanceOf will cast a Fragment into your Fragment class. It was you, who suggested Fragment1 as a name for simpicity. Also, you didn't provide any source to help us. It is true, that you cannot set a Fragment's tag, but why do you think you are able to get its tag?
Usually a Fragment is added through FragmentManagers like
FragmentManager manager = getSupportedFragmnentManager()
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(int containerViewId, Fragment fragment, String tag);
// or transaction.add(Fragment fragment, String tag)
// ...other transactions
transaction.commit()
EDIT2: it's very easy though. according to your code you could just call
Fragment fragment = mAdapter.getItem(0) // 0||1||2
You should consider reading the docs (i.e about FragmenPagerAdapter) and post your source code so we don't have to guess what you need.

I had the same issue but fixed it with a localBroadcastReceiver like this:
Create a receiver in your activity and register it:
/**
* ******************************
* Receiver to process the message
* *******************************
*/
private BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//You can send any extra data if you need like this
final int type = intent.getIntExtra("fragment.data", -1);
Log.d(tag, "main class: " + type);
//also refresh your fragment like this
mViewPager.getViewPager().getAdapter().notifyDataSetChanged();
}
};
#Override
protected void onResume() {
super.onResume();
//Register a localbroadCast with the your filter
IntentFilter thinaireFilter = new IntentFilter("your.filter");
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, thinaireFilter);
}
Remember to remove LocalBroadCast
//remove the LocalBroadCast when no need it
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
}
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
}
Send your broadcast from anywhere you want Adapters, services, etc.
Intent sendBroadCastData = new Intent("your.filter");
sendBroadCastData.putExtra("fragment.data", myData);
LocalBroadcastManager.getInstance(context).sendBroadcast(sendBroadCastData);
Hope it helps others.

I don't know enough of what you are doing, but it sounds like you need to use an Observer pattern, Callbacks, or Listeners. Can't your fragment just do somthing like:
myservice.addMyEventListener(myFragInstance);
and then you can be "notified of a specific event."

Just look at this answer https://stackoverflow.com/a/16388650
He has used yourAdapter.notifyDataSetChanged() which is a predefined method.
Check the link to see how its done
Edit:
When your AsyncTask is done, you should do something like this onPostExecute method:
ResultFragment resultFrag = (ResultFragment) getSupportFragmentManager()
.findFragmentByTag("FragToRefresh");
if (resultFrag != null) {
resultFrag.refreshData(refreshedArray);
}
And in your ResultFragment you need to have refreshData method, which is something like this:
public void refreshData(ArrayList<YourObject> data) {
yourArray = new ArrayList<YourObject>(data);
yourAdapter.notifyDataSetChanged();
}

Had to use event bus to make everything simple https://github.com/greenrobot/EventBus

I am not sure this is the right way of doing it
1. Create a public function in fragment you would call to receive the data.
public void refreshList(List<String> yourData) {
//referesh your fragment views here
}
2. Create the fragment object global
YourFragment frag = new YourFragment();
3. Pass it to the view pager in the containing activity
4. Add on page change listener to the view pager
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
break;
case 1:
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Here case 0: would be invoked when first fragment is selected and case 1: when second and so on..
5. Call your function corresponding to its position in the view pager
case 0: frag.refreshList(yourList);

Related

How to update a Fragment that has a Gridview populated from Sqlite

I have a ViewPager with two tabs which holds fragment. Inside the first fragment, I have a Gridview which is being populated with Sqlite Db.
I have an custom alertdialog in my Activity, which is the parent of the Fragments.
When the alertdialog closes, it either adds/removes/updates the Sqlite Db:
DataBaseHelper dbh = DataBaseHelper(this);
...
positiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbh.addVal(new TheData(editName.getText().toString(), editAge.getText().toString())); //adds a row to the Sqlite Db
dialog.dismiss();
//on dismiss, refresh the Fragment, which in turn will display the updated GridView.
}
});
...
How can I update complete the following:
//on dismiss, refresh the Fragment, which in turn will display the updated GridView.
You could use Intents and Intent Filters with a Broadcast Receiver
for this.
Create a BroadcastReceiver instance in the fragment where you want to update the data.
Create an IntentFilter and set an action string (maybe 'db.update') to it and register it with your application context (you could do this via your fragment by calling getActivity().getApplicationContext().registerReceiver(receiver, filter).
In your AlertDialog, after you update your database, create an Intent with the same action string you set above (in our case, 'db.update') and use context to send it out (getActivity().getApplicationContext().sendBroadcast(intent)). Your BroadcastReceiver's onReceive() method would be called in your fragment and you can call the method to refresh or reload your data there. See sample code below:
Say this is your fragment
public class YourFragment extends Fragment {
private GridView mGridView;
private BaseAdapter mAdapter;
private BroadcastReceiver mReceiver;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//inflate view as usual
View view = inflater.inflate(R.layout.yourlayour, container, false);
...
//create instance of broadcast receiver
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) { //when intent is receiver, this method is called
if(intent.getAction().contentEquals("db.update")){
//update intent received, call method to refresh your content loader
refreshFragment();
}
}
};
//create a new intent filter
IntentFilter mDataUpdateFilter = new IntentFilter("db.update");
//register our broadcast receiver and intent filter
getActivity().getApplicationContext().registerReceiver(mReceiver, mDataUpdateFilter);
return view;
}
#Override
public void onDestroy() {
super.onDestroy();
//never forget to unregister the receiver when you're done, it could cause your app to crash
//if it receives an intent and calls null pointing methods in your code
getActivity().getApplicationContext().unregisterReceiver(mReceiver);
} }
Then in your AlertDialog as you did above, send the intent to this receiver by:
DataBaseHelper dbh = DataBaseHelper(this);
...
positiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbh.addVal(new TheData(editName.getText().toString(), editAge.getText().toString())); //adds a row to the Sqlite Db
//Create an intent with our action
Intent updateIntent = new Intent("db.update");
//send the intent by
getContext().getApplicationContext().sendBroadcast(updateIntent);
dialog.dismiss();
}
});
...
Don't forget to unregister your broadcast receiver when your fragment is destroyed. Call getActivity().getApplicationContext().unregisterReceiver(receiver); in your onDestroy() method.
I should also point out that the onReceive() method of your broadcast receiver would always be called on the main thread, even if you send your intent from a background thread.
Here is a trick that i use to access Fragments inside a ViewPager
in my custom viewPagerAdapter, i add two methods
public class CustomViewPagerAdapter extends FragmentPagerAdapter {
.....
private String getFragmentTag(int viewId, int index) {
return "android:switcher:" + viewId + ":" + index;
}
//mFragManager is a reference to FragmentManager
public Fragment getFragmentByTag(int containerId, int position) {
return mFragManager.findFragmentByTag(getFragmentTag(containerId, position));
}
}
then in your activity or wherever you can access the customViewPager
YourFragment frag = (YourFragment) customViewPager
.getFragmentByTag(YouViewPager.getId(), position);
after that, add a method in YourFragment refreshData (if you like the name!) and in it refresh the grid
Hope this help
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(frag).attach(frag).commit(); //frag is my Fragment instance...
Each time the dialog closed and it did the trick... simple and easy!

ViewPager and FragmentPagerAdapter: how to notify the fragment instance that it's being switched to another fragment?

I have a ViewPager, FragmentPagerAdapter and a couple fragments. I need to notify the fragment when the user switches to a different one (so that the first one can finalize its work). I'm looking into ViewPager.OnPageChangeListener but can't see any way to get the current fragment instance when the change occurs. Even ViewPager.getCurrentItem() returns the new position when OnPageChangeListener.onPageSelected is called.
Is it guaranteed that Fragment.onPause() will be called for the previous fragment every time when a new one is selected? That would certainly simplify things.
According to documentation is seems onPause gets call when ever user leave the fragment (though it does not always mean the fragment is being destroyed).
https://developer.android.com/guide/components/fragments.html
You can keep a reference of your fragment at class level, as mCustomFragment.
Then inside your fragment setup a public method which will finalize the work, you simply call this method when you need it in the ViewPager.OnPageChangeListener.
Maybe attach some sort of gesture listener to determine which way the swipe occurs. Then on OnPageChangeListener based on the last gesture used before the call, determine whether to put +1 or -1 on the current viewpager index.
Here's my solution that actually works. It involves broadcasts for notifying the fragments.
First, I extended the Fragment class:
#SuppressLint("ValidFragment")
public class ExtendedFragment extends Fragment {
public static final String FragmentIdTag = "Fragment ID";
public static final String FragmentSwitchedEventId = "FragmentSwitchedEvent";
#SuppressLint("ValidFragment")
protected ExtendedFragment(FragmentType fragmentId) {
m_fragmentType = fragmentId;
}
public void onSwitchedAway() {
}
public BroadcastReceiver broadcastReceiver() {
return m_receiver;
}
class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
FragmentType newFragmentType = (FragmentType) intent.getSerializableExtra(FragmentIdTag);
if (newFragmentType != m_fragmentType)
onSwitchedAway();
}
}
protected final FragmentType m_fragmentType;
Receiver m_receiver = new Receiver();
}
FragmentType is enum that's different for every fragment. All the fragments extend ExtendedFragment (a terrible name, I know. Feel free to suggest a better one) and pass appropriate unique FragmentType value to its constructor.
Then I use the Viewpager.OnPageChangeListener to detect the fragment switch:
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {
FragmentType newType = fragmentTypeForPosition(position);
Intent i = new Intent(ExtendedFragment.FragmentSwitchedEventId);
i.putExtra(ExtendedFragment.FragmentIdTag, newType);
LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(i);
}
#Override
public void onPageScrollStateChanged(int state) {}
});
And finally, when instantiating the fragments don't forget to register them as broadcast receivers:
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
FragmentType newType = fragmentTypeForPosition(position);
Intent i = new Intent(ExtendedFragment.FragmentSwitchedEventId);
i.putExtra(ExtendedFragment.FragmentIdTag, newType);
LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(i);
}
});
Done. Now the fragments can override public void onSwitchedAway().

Pass data from A and B fragments to C fragements

I have created three fragments A, B and C. In fragment A I'm having First Name and Last Name. In fragment B I'm having Age, City, Area and Address. In C I'm having Profession and Experience. In frag C I'm also having a button which sends all the info to the server. Now how can I have the info from fragment A and B in fragment C. I have used Bundle to send the info but it's a tedious task. Any simple method available?
E.g.:
Bundle args = new Bundle ();
args.putString ("first_name", strFirstName);
args.putString ("last_name", strLastName);
Instead of passing data from fragment A and B to C, pass them to the Activity via callback, and then pass the "send to server" action callback so that the Activity handles it:
class Fragment A {
// fragment definition
public interface OnUserInformationTypedListener {
public void onUserInformationTyped(String name, String lastName);
}
}
class FragmentB {
// fragment definition
public interface OnUserExtraInformationTypedListener {
public void onUserExtraInformationTyped(int age, String address);
}
}
class FragmentC {
// fragment definition
public interface OnUserCareerInformationTypedListener {
public void onUserCareerTyped(String profession, String experience);
public void onSendToServer();
}
}
Then make the Activity implements all interfaces:
class MyActivity extends Activity implements OnUserInformationTypedListener,
OnUserExtraInformationTypedListener, OnUserCareerInformationTypedListener {
#Override
public void onUserInformationTypedListener(String name, String lastName) {
// Probably pass local variable to private attributes
}
// Override the rest of the interface's methods
#Override
public void onSendToServer() {
// Send information to the server logic
}
}
And finally, make the FragmentA, FragmentB and FragmentC each one an instance of their respective callback, i.e:
// Inside FragmentA
private OnUserInformationTypedListener listener = null;
And then you pass the listener reference to it, Either by calling Fragment#onAttach(Activity) or via public method:
// Inside FragmentA
#Override
public void onAttach(Activity activity) {
listener = (OnUserInformationTypedListener) activity;
}
// if you prefer public setter then create the setter and call it from the Activity:
// Inside Activity#onCreate or wherever you instantiate the fragment
FragmentA fa = new FragmentA();
fa.setOnUserInformationTypedListener(this);
For more information on how to communicate Fragments via the host Activity (this is the right way to do it), read this http://developer.android.com/training/basics/fragments/communicating.html
The Fragment documentation says:
Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
So, its not a good idea to pass message from one fragment to another. Check the basics fragment training docs
Any simple method available?
You can save the data in a common class, and access the same from the other fragments..
use this i want to pass data on button click like this
btn_camera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
}
});
and get data oncreate method of fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}

Call fragment from another fragment after some delay

I searched all over the web, couldn't find a good reference on how to call fragment from another fragment.
Fragment A -> Fragment B (fragment A calls fragment B after 3 seconds)
Well, first of all you need to consider that it's a very bad idea to keep somehow a direct reference from FragmentA to FragmentB. Why:
FragmentB may be recreated and you may keep a reference to an older reference of FragmentB. So you have a memory leak.
FragmentB may be not created, added or visible. So you would have a null/unusable reference.
For this reason you need to consider methods that base on sending messages from FragmentA to FragmentB. I see several options:
Send a broadcast message using a custom action from FragmentA. FragmentB registers itself as a receiver for this kind of message (in onCreate/onResume/onAttach and de-register in onDestroy/onPause/onDetach) and when the message arrives it can handle it. This is very suitable if you have no data to send from FragmentA to FragmentB or if you do these are primitive types or easy-to-implement Parcelables. Here's an example:
Have this in FragmentA:
private void sendMessageToFragmentB(String someData) {
Intent messageIntent = new Intent("com.your_package.A_TO_B_ACTION");
messageIntent.putExtra("DATA_VALUE", someData);
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(messageIntent);
}
While in FragmentB you could have this:
public class FragmentB extends Fragment {
private BroadcastReceiver messagesFromAReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if ("com.your_package.A_TO_B_ACTION".equals(intent.getAction())) {
String dataFromA = intent.getStringExtra("DATA_VALUE");
dataFromAReceived(dataFromA);
}
}
};
protected void dataFromAReceived(String data) {
// here you have the data
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
IntentFilter messageFromAIntentFilter = new IntentFilter("com.your_package.A_TO_B_ACTION");
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(messagesFromAReceiver,
messageFromAIntentFilter);
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(messagesFromAReceiver);
}
}
Use the hosting activity as a proxy: The host activity implements some kind of interface defined in FragmentA and when requested it can search if it can find FragmentB and if so call some method in there. The advantage is that you can send any data, no matter its weight. The base idea is descrived in Android dev articles. To exemplify, you could have FragmentA as:
public class FragmentA extends Fragment {
public static interface CallerProxy {
public void sendCustomMessage(Object... dataParams);
}
private CallerProxy proxyActivity;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof CallerProxy) {
this.proxyActivity = (CallerProxy) activity;
}
}
#Override
public void onDetach() {
super.onDetach();
this.proxyActivity = null;
}
private void sendMessageToFragmentB(String someData) {
if (proxyActivity != null) {
// send whatever data
proxyActivity.sendCustomMessage(new Integer(1), new Object());
// or don't send anything ...
proxyActivity.sendCustomMessage();
}
}
}
The proxy activity would have at least these methods and signature:
public class MyProxyActivity extends FragmentActivity implements CallerProxy {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// call setContentView and then make sure you've added FragmentA and
// FragmentB.
}
#Override
public void sendCustomMessage(Object... dataParams) {
// FragmentB must be identified somehow, either by tag,
// either by id. Suppose you'll identify by tag. This means you've added
// it previously with this tag
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentB-TAG");
if (fragment != null) {
FragmentB fragB = (FragmentB) fragment;
fragB.dataFromAReceived(dataParams);
}
}
}
While in FragmentB all you need is a method that can be called with above sent parameters:
public void dataFromAReceived(Object ... data) {
// here you have the data
}
Use or implement some sort of event bus. Some general details here. For Android I remember that Otto event bus was very handy and easy to use. Here's a link with this. This is very similar to first option as you need anyway to register and un-register.
In the end it depends on what you need to send as a message, when should it be received and how flexible does it need to be. ... your choice!
Enjoy programming!
Fragments are not supposed to connect to each other directly, that may be your problem in finding a decent guide to do this.
Your approach makes the assumption that a fragment B will always be reachable (and ready) for a fragment A to interact, and that is actually not true, will kill the flexibility of your Fragment and will cause you problems in the future.
A better approach to interaction of Fragments is to talk only through interfaces that talk directly to a activity that can handle who is alive when where and should receive what.
-> http://developer.android.com/training/basics/fragments/index.html
This Android guide above, specifically on the last topic, shows you how to do this.
i hope this code help you..
in your first fragment add this code
onCreateView
LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity());
IntentFilter intentFilter = new IntentFilter("update");
// Here you can add additional actions which then would be received by the BroadcastReceiver
broadcastManager.registerReceiver(receiver, intentFilter);
#Override
public void onDestroyView() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onDestroyView();
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null && action.equals("update")) {
// perform your update
getOngoingOrderData();
}
}
};
in your second fragment add this code where you send broadcast..
Intent intent = new Intent("update");
LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity());
broadcastManager.sendBroadcast(intent);

deep copy of Fragment

I am using a Fragment class.
I add it using
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Search fragment = new Search(maincontrolActivity.this);
fragmentTransaction.add(R.id.mainLayout,fragment , "MY_FRAG");
fragmentTransaction.commit();
this.FragmentObject = fragment
when I do refresh the control,I recall this code but by passing this.FragmentObject but I think it be garbage collected because the = refere to the same object , and when say add, it free the old fragement which is the same
so do I need a deep copy or any way to refresh ?
any idea
Ok. So what I would do is have an Interface defined and have each Fragment register with the Activity for a callback when the refresh button is clicked. Then in the fragment itself have it refresh its data. If that means getting new data, switch to a ProgressBar, get the data from the server, and repopulate the Views. Here is an entire article on creating Interfaces in Activities and calling Fragments from them.
Here is roughly what your code will look like...
The Activity:
public class RefreshActivity extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViewById(R.id.refresh_button).setOnClickListener(this);
}
public interface OnRefreshPressedListener {
public void onRefreshPressed();
}
#Override
public void onClick(View v) {
((OnRefreshPressedListener)this.FragmentObject).onRefreshPressed();
}
}
The Fragment:
public class Search extends Fragment implements OnRefreshPressedListener {
#Override
public void onRefreshPressed() {
//TODO: Refresh your data!
}
}

Categories

Resources