I'm using Bottom-navigation with 3 fragments. On Home-fragment I'm requesting API to fetch data and show in recycler-view my problem is whenever I switch fragments and come again to Home-fragment it's recreating the layout and again its fetch data from API I want to load only one time when app launch
This is where I call API in the fragment
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment, container, false);
// return inflater.inflate(R.layout.home_fragment, container, false);
sharedPrefManager = new SharedPrefManager(getActivity());
locationTrack = new LocationTrack(getActivity());
buildGoogleApiClient();
fusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
getUserLatLng();
setUp(view);
netWorkCall();
return view;
}
HomeActivity to load home-fragment by default
if (savedInstanceState == null) {
Fragment fragment = null;
fragment = new HomeFragment();
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.content_frame, fragment, "home").addToBackStack("Home");
ft.commit();
}
}
bottom-navigation click listener
private void displaySelectedScreen(int itemId) {
Fragment fragment = null;
switch (itemId) {
case R.id.action_home:
fragment = new HomeFragment();
break;
case R.id.action_profile:
if (sharedPrefManager.getAuthority()) {
fragment = new ProfileFragment();
} else {
SDConstant.switchActivity(this, LoginScreen.class);
}
break;
case R.id.action_calculator:
if (sharedPrefManager.getAuthority()) {
fragment = new CalculatorFragment();
} else {
SDConstant.switchActivity(this, LoginScreen.class);
}
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment, "home").addToBackStack("Home");
ft.commitAllowingStateLoss();
//ft.commitNow();
}
}
}
Please guide me solution How to solve this re-creation API call
First off, perform this calls inside onViewCreated instead of onCreateView:
sharedPrefManager = new SharedPrefManager(getActivity());
locationTrack = new LocationTrack(getActivity());
buildGoogleApiClient();
fusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
getUserLatLng();
setUp(view);
netWorkCall(); //this call has to be removed as explained later
Why? Because onCreateView should just return the fragments UI. OnViewCreated is called directly afterwards and this is the place to do some stuff.
No to get to your problem. The best way for you to solve this would be using a ViewModel from the architecture components in conjunction with LiveData.
You can read more on this topic here.
Your implementation could look like this (adapted the example from the link):
public class MyViewModel extends ViewModel {
private MutableLiveData<List<User>> users;
public LiveData<List<User>> getUsers() {
if (users == null) {
users = new MutableLiveData<List<User>>();
loadUsers();
}
return users;
}
private void loadUsers() {
// Do an asynchronous operation to fetch users.
}
}
In your onViewCreated you can do something lik this:
MyViewModel model = new ViewModelProvider(getViewLifecycleOwner()).get(MyViewModel.class);
model.getUsers().observe(getViewLifecycleOwner(), users -> {
// update UI
});
Don't feel overwhelmed by this. What it does in reality is relatively simple. The ViewModel survives configuration changes. Meaning if you rotate your phone the loadUsers request won't be invoked again - same with switching between bottom navigation tabs. Of course If the fragment is destroyed, the ViewModel does also get destroyed (the function onCleared is invoekd then).
The LiveData users is just a fancy name for a simple observer. Mutable means that you can set a value, getUsers() returns a non mutable LiveData, this means you can only read its value. When you set a value to a LiveData object, it's subscriber will be notified. You can imagine it like the LiveData is an interface implmented by your Fragment which is using the ViewModel. And this interfaces function is invoked once you have fetched data. More info on dealing with LiveData is explained here you should definitely check it out.
So the ViewModel will invoke loadUsers once you start observing getUsers if the Users have not been loaded yet. If they have been loaded, the current value is returned.
Oh and to add LiveData and ViewModel -> it's explained here :)
Hope this was helpful. I know it is alot but trust me it is worth investing the time!
Related
shared element transition replace the fragment, so I can't add it to the backstack and call popbackstack when the back arrow button is pressed.
I have a main activity with inside a mainfragment, the main fragment handle a table layout so each tab is a fragment with inside a recycler view, when a recycler view element is clicked the shared element transition start to a new fragment that shows element details.
This is the adapter, where the element is clicked:
holder.image.setTransitionName("transition" + holder.getAdapterPosition());
if (fragment instanceof tab1_anime) {
((tab1_anime) fragment).openShowElementFragment(holder.getAdapterPosition(), v.findViewById(R.id.main_image));
}
This is the openShowElementFragment inside my tab fragment:
public void openShowElementFragment(int position, View view) {
AddElement element = anime_list.get(position);
ShowElementFragment showElementFragment = new ShowElementFragment();
Bundle bundle = new Bundle();
bundle.putString("transitionName", "transition" + position);
bundle.putSerializable("element", element);
bundle.putInt("position", position);
bundle.putInt("from", 0);
showElementFragment.setArguments(bundle);
((MainActivity) context).showFragmentWithTransition(this, showElementFragment, "showElementFragment", view, "transition" + position);
}
this is the openshowelementfragment function called in the previous code block:
public void showFragmentWithTransition(Fragment current, Fragment newFragment, String tag, View sharedView, String sharedElementName) {
FragmentManager fragmentManager = getSupportFragmentManager();
// check if the fragment is in back stack
boolean fragmentPopped = fragmentManager.popBackStackImmediate(tag, 0);
if (fragmentPopped) {
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
current.setSharedElementReturnTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
current.setExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
}
fragmentManager.beginTransaction()
.replace(R.id.fragmentHolder, newFragment)
.addToBackStack(null)
.addSharedElement(sharedView, sharedElementName)
.commit();
}
}
and this is the backarrow button:
back_arrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getSupportFragmentManager().popBackStack();
}
});
If I try to add the new fragment instead of replace the old one, then there is not animations at all.
If I try to replace the old fragment with the new one and using anyway the addtobackstack(null) then the shared element transition works from start to end BUT the fragment at the end is without data, empty:
I tried also:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentHolder, new MainFragment())
.addToBackStack(null)
.commit();
but in this way the shared element transition doesn't work on exit:
I think your problem is related to exit transition as you get solution of empty list, now for exit transition effect check below code.
public void showFragmentWithTransition(Fragment current, Fragment newFragment, String tag, View sharedView, String sharedElementName) {
FragmentManager fragmentManager = getSupportFragmentManager();
// check if the fragment is in back stack
boolean fragmentPopped = fragmentManager.popBackStackImmediate(tag, 0);
if (fragmentPopped) {
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
current.setSharedElementReturnTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
current.setExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setSharedElementReturnTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
}
getSupportFragmentManager().beginTransaction()
.addSharedElement(sharedElement, transitionName)
.replace(R.id.container, newFragment)
.addToBackStack(null)
.commit();
}
}
Here I add two new lines for exit transitions.
newFragment.setExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setSharedElementReturnTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
If its not work then follow below link, I think it will help you.
https://medium.com/#bherbst/fragment-transitions-with-shared-elements-7c7d71d31cbb
Your so called sharedElementName is actually a transitionName.
a) The reference example doesn't directly manipulate the backstack:
Android Fragment Transitions: RecyclerView to ViewPager & Blog.
b) Manual transactions might require another order of method calls:
getSupportFragmentManager().beginTransaction()
.addSharedElement(sharedElement, transitionName)
.replace(R.id.container, newFragment)
.addToBackStack(null)
.commit();
Also see this example, how alternate transitions could be be set, compared to:
TransitionInflater.from(this).inflateTransition(R.transition.default_transition)
Whatever R.transition.default_transition may be.
It may look strange when using the same transition for both ways, instead of enter/exit transitions, alike NavAction would feature. FragmentNavigator.Extras could be used to apply enter/exit transitions, when using navigation component; this also can be combined with ActionBar. Option a) is probably less complicated. b) something alike this Kotlin example might make more sense.
It's pointless to build clunky navigation FX when enter/exit transitions would be supported out-of-the-box. Maybe consider loading with Glide, when loading images.
Assume the following build.gradle; there's no need to reinvent the wheel.
dependencies {
androidTestImplementation "androidx.navigation:navigation-testing:2.5.3"
implementation 'androidx.navigation:navigation-runtime:2.5.3'
implementation 'androidx.navigation:navigation-fragment:2.5.3'
implementation 'androidx.navigation:navigation-ui:2.5.3'
annotationProcessor 'com.github.bumptech.glide:compiler:4.14.2'
implementation 'com.github.bumptech.glide:glide:4.14.2'
}
Then Navigation with FragmentNavigator.Extras might rather be the current method:
Bundle navArgs = new Bundle();
navArgs.putInt("position", position);
FragmentNavigator.Extras extras = new FragmentNavigator.Extras.Builder()
.addSharedElement(sharedElement, transitionName)
.build();
Navigation.findNavController(view).navigate(
R.id.details, // ID of Nav destination
navArgs, // Bundle of args
null, // NavOptions
extras);
One can also define transitionName in XML <action/> nodes.
I have a Fragment inside the mainActivity, the fragment contains fragmentcontainerView which can be replaced by multiple child fragments with spinner onselectedListener. I want to able to pass those values from the child fragment via eg: Do something with: fragmentevent.TogetFName(); with a button in Mainactivity. In the parent fragment , I get the value from the child fragment(fragment_Birthday) with fragment_fr_event_birthday = (fragment_fr_event_Birthday) getChildFragmentManager().findFragmentById(R.id.fragment_event_child_fragment); and other value from other childfragment with frag_fr_event_wed = (fragment_fr_event_wedding) getChildFragmentManager().findFragmentById(R.id.fragment_event_child_fragment);, I know that they cannot be assigned with the different fragment class at once, but is there a clever way to do this or is there any other way I can pass value from child -> parent fragment->mainActivity
MainActivity:
public void onClick(View view){
case "Event":
Fragment_fr_Event fragment_fr_event = (Fragment_fr_Event) getSupportFragmentManager().findFragmentById(R.id.fragment_generated_mainView);
if(fragment_fr_event.TogetWedChildFcoupleName() !=null && fragment_fr_event.TogetEventType().equals("Wedding")){
testThis.setText(fragment_fr_event.TogetWedChildFcoupleName());
}if( fragment_fr_event.TogetEventType().equals("Birthday") && fragment_fr_event.TogetBirthdayFName() !=null){
testTat.setText(fragment_fr_event.TogetBirthdayFName());
}
}
ChildFragment(BirthdayFragment):
public String TogetEventBirthdayFName (){
EditText FBirthdayName = rootView.findViewById(R.id.Edittext_birthDay_FirstName);
return FBirthdayName.getText().toString();
}
ChildFragment(Wedding fragment):
public String toGetFcoupleName(){
EditText FCoupleName = rootView.findViewById(R.id.textView_wedding_Name);
return FCoupleName.getText().toString();
}
ParentFragment(EventFragment):
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Spinner TypeEventSpinner = rootview.findViewById(R.id.type_event);
TypeEventSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String tag_items = parent.getItemAtPosition(position).toString();
switch (tag_items){
case "Wedding":
frag_fr_event_wed = new fragment_fr_event_wedding();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_event_child_fragment, frag_fr_event_wed).disallowAddToBackStack().commit();
break;
case "Birthday":
fragment_fr_event_birthday = new fragment_fr_event_Birthday();
transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_event_child_fragment , fragment_fr_event_birthday).disallowAddToBackStack().commit();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public String TogetWedChildFcoupleName(){
if(frag_fr_event_wed !=null){
frag_fr_event_wed = (fragment_fr_event_wedding) getChildFragmentManager().findFragmentById(R.id.fragment_event_child_fragment);
return frag_fr_event_wed.toGetFcoupleName();
}return "Empty";
}
public String TogetBirthdayFName(){
if(fragment_fr_event_birthday != null){
fragment_fr_event_birthday = (fragment_fr_event_Birthday) getChildFragmentManager().findFragmentById(R.id.fragment_event_child_fragment);
return fragment_fr_event_birthday.TogetEventBirthdayFName();
}
return "Empty";
}
To be honest , I couldn't understand what you did there , but i got what you want , you want to communicate with parent's parent class , the way you are doing it made it so complicated even it's not readable , BUT of course there are always a good way to do something , in your case there are Android Navigation Component , which give you the simplicity and power to do make it much more easy to handle , You can put all your fragment in one graph and from within the destinations "fragment are called destinations here" you can communicate with other fragment and the parent using actions and global actions "going from one fragment to another is called action here" parameters, but there are no need to a parent's parent here , all destinations and its parent can share one ViewModel which will allow you to share data all around your app .
You can read more if it sound good to you here
I've been stuck on this for a while now and will appreciate any guidance on this. Also not sure if my title is accurate. Inside my adapter I create a new fragment:
Adapter code:
cardAdoptDetailsFrag nextFrag = new cardAdoptDetailsFrag();
android.support.v4.app.Fragment callingFrag = ((FragmentActivity)context).getSupportFragmentManager().findFragmentByTag("TagFeedFragment");
FragmentTransaction ft = ((FragmentActivity)context).getSupportFragmentManager().beginTransaction();
ft.hide(callingFrag);
ft.add(R.id.fram, nextFrag,"cardAdoptDetailsFrag");
ft.addToBackStack("TagFeedFragment");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
Then inside my Main Activity where I manage all the fragments, I'm trying to check if the "cardAdoptDetailsFrag" isAdded. For some reason I cannot do it as per the below.
Get Fragment by tag. The below is where it fails with null object reference.
Fragment frag = getSupportFragmentManager().findFragmentByTag("cardAdoptDetailsFrag");
Log.d(TAG, "Check if added: "+frag.isAdded());
Now I know I can just add it inside a method and do a null check and return a boolean, but I know I'm doing something wrong here. Because with my other fragments the isAdded and remove works, but they get initiated inside the Main Activity where "cardAdoptDetailsFrag" gets initiated inside the adapter.
Example of Main Activity:
public class MainActivity extends AppCompatActivity implements adoptFeedFragment.OnFragmentInteractionListener,
lostAndFoundFragment.OnFragmentInteractionListener,
servicesFragment.OnFragmentInteractionListener,
userMenuFragment.OnFragmentInteractionListener,
showUserAdoptPostsFrag.OnFragmentInteractionListener{
adoptFeedFragment adoptFeedFragment;
lostAndFoundFragment lostAndFoundFragment;
servicesFragment servicesFragment;
userMenuFragment userMenuFragment;
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adoptFeedFragment = new adoptFeedFragment();
lostAndFoundFragment = new lostAndFoundFragment();
servicesFragment = new servicesFragment();
userMenuFragment = new userMenuFragment();
....
//Here I can do for example:
adoptFeedFragment.isAdded(); //Will simply return a boolean.
//Or I can do a remove:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.remove(adoptFeedFragment);
//But I cannot do the below:
Fragment frag = getSupportFragmentManager().findFragmentByTag("cardAdoptDetailsFrag");
Log.d(TAG, "frag.isAdded(): "+frag.isAdded());
*****Edited Post. Ok lets say the frag is added. Why can I not remove it using the below.
public boolean isAdoptDetailsFragAdded() {
Fragment frag = getSupportFragmentManager().findFragmentByTag("cardAdoptDetailsFrag");
if(frag == null){
return false;
} else {
return true;
}
}
public Fragment getAdoptDetailsFrag() {
return getSupportFragmentManager().findFragmentByTag("cardAdoptDetailsFrag");
}
//I'm unable to remove the fragment using the below:
Log.d(TAG, "showFeedFragment: "+isAdoptDetailsFragAdded()); <--returns true
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(isAdoptDetailsFragAdded()) {
ft.remove(getAdoptDetailsFrag());
}
ft.commit();
//Now I check again wether it is still added. And still returns true even though I just removed it.
Log.d(TAG, "showFeedFragment: "+isAdoptDetailsFragAdded()); <-- Still returns true.
}
This is my fragment adding or replacing method which i am using in 13 projects.
You can use it and get rid of managing fragments.
/**
* replace or add fragment to the container
*
* #param fragment pass android.support.v4.app.Fragment
* #param bundle pass your extra bundle if any
* #param popBackStack if true it will clear back stack
* #param findInStack if true it will load old fragment if found
*/
public void replaceFragment(Fragment fragment, #Nullable Bundle bundle, boolean popBackStack, boolean findInStack) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
String tag = fragment.getClass().getName();
Fragment parentFragment;
if (findInStack && fm.findFragmentByTag(tag) != null) {
parentFragment = fm.findFragmentByTag(tag);
} else {
parentFragment = fragment;
}
// if user passes the #bundle in not null, then can be added to the fragment
if (bundle != null)
parentFragment.setArguments(bundle);
else parentFragment.setArguments(null);
// this is for the very first fragment not to be added into the back stack.
if (popBackStack) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
ft.addToBackStack(parentFragment.getClass().getName() + "");
}
ft.replace(R.id.main_frame_container, parentFragment, tag);
ft.commit();
fm.executePendingTransactions();
}
Here R.id.main_frame_container is FrameLayout in activity layout on which fragment is placed.
Here findFragmentByTag() is returning null when you do getSupportFragmentManager().findFragmentByTag("cardAdoptDetailsFrag").
findFragmentByTag() will return null in two cases.
If fragment cardAdoptDetailsFrag is not yet attached to view (you did not call add or replace for this fragment)
You added that fragment, but you are using different TAG, while searching that fragment.
Make sure if non of the case in your problem.
Now the solution is, you can modify your logic, like
Fragment frag = getSupportFragmentManager().findFragmentByTag("cardAdoptDetailsFrag");
if (frag != null && frag.isAdded()) {
// Do you task. Fragment is added
} else {
// Fragment is not added yet
}
I did not went through the long post but I read only this part.
Now I check again wether it is still added. And still returns true even though I just removed it.
And the reason behind that is FragmentTransaction.commit is not synchronous.
Read the docs for commit method:
*Schedules a commit of this transaction. The commit does
* not happen immediately; it will be scheduled as work on the main thread
* to be done the next time that thread is ready.*
If you need that to be synchronous, use commitNow instead.
I am basically playing an animation on each fragment of the view pager. The animation plays when the user slides to the specific fragment. However, certain fragments don't play the animation the second time I visit them. That's because the view pager keeps them in memory.
I need to destroy each fragment after the user slides to another fragment. This way, the animations play every time I revisit those fragments.
Main View:
pager = (ViewPager) findViewById(R.id.guidepager);
mAdapter = new NewUserGuideAdapter(getSupportFragmentManager());
pager.setAdapter(mAdapter);
pager.setOffscreenPageLimit(0); //Tried this too. Didnt work
Fragment:
public class NewUserPage_Two extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_new_user_page__two, container, false);
//Play animation, etc
Animation animation_1 = AnimationUtils.loadAnimation(NewUserPage_Two.this.getActivity(), R.anim.abc_slide_in_bottom);
person1.setAnimation(animation_1);
return rootView;
}
Adapter:
public class NewUserGuideAdapter extends FragmentPagerAdapter {
public NewUserGuideAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new NewUserPage_One();
case 1:
return new NewUserPage_Two();
case 2:
return new NewUserPage_Three();
case 3:
return new NewUserPage_One();
case 4:
return new NewUserPage_One();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 5;
}
}
How can I amend my code guys?
ViewPager provide a method mViewPager.setOffscreenPageLimit(0);
Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.
Try this inside the fragment:
((BaseAdapter) *YourContainer*.getAdapter()).notifyDataSetChanged();
You can refer to: Refresh Current Fragment (ListView Data) remaining in the same activity
public void setOffscreenPageLimit(int limit) {
if (limit < DEFAULT_OFFSCREEN_PAGES) {
Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " +
DEFAULT_OFFSCREEN_PAGES);
limit = DEFAULT_OFFSCREEN_PAGES;
}
if (limit != mOffscreenPageLimit) {
mOffscreenPageLimit = limit;
populate();
}
}
That's the method body,DEFAULT_OFFSCREEN_PAGES=1by the way.I think google add this limits cause you need at least the 2 views between current item while you are sliding.
You can try using addOnPageChangeListener() and start your animation on onPageSelected.
I am pretty new to Android (3 days), but I have a pretty good background in PHP (which may be the cause of my confusion in a Java based environment). I started building an Android app using Android Studio (Beta). I created the default Android Studio activity with the Navigation Drawer Activity. I edited the activity fragment part to look like this:
#Override
public void onNavigationDrawerItemSelected(int position) {
Bundle bundle = new Bundle();
bundle.putStringArrayList("contacts", arr);
bundle.putStringArrayList("messages", messages);
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FriendsFragment();
break;
case 1:
fragment = new ChatsFragment();
break;
case 2:
fragment = new GroupsFragment();
break;
case 3:
fragment = new LogoutFragment();
break;
default:
break;
}
if (fragment != null) {
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).addToBackStack(null).commit();
}
}
As you can see I am passing a Bundle to my Fragments called "messages" and "contacts" when an item is selected in the Navigation Drawer. The "messages" bundle are XMPP messages received by the aSmack library from an OpenFire server. So basically I'm trying to create a XMPP client. When I run the app I can receive the messages in the "ChatsFragment".
Now my problem:
I have to press the "ChatsFragment" item on the drawer to have my messages updated (re-receive the bundle) everytime I feel like there are new messages received from the server. But I want this to be done automatically by the fragment.
First I would like to know if my procedure is correct (Activity listens to server, creates bundle, send bundle to fragment, bundle updates messages on receive**)
** = This part I haven't been able to understand how to implement.
1- If the procedure is correct tell me how I should get the messages to be updated by the fragment through the activity?
2- If this is not the correct way to do things in Android, recommend me a way of doing it.
My code for displaying the messages in fragment:
private void displayListView() {
// Messages array list
List<String> contacts = getArguments().getStringArrayList("messages");
//System.out.println("arr: " + contacts);
//create an ArrayAdaptar from the String Array
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),
R.layout.url_list, contacts);
ListView listView = (ListView) getView().findViewById(R.id.listView);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
//enables filtering for the contents of the given ListView
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Send the URL to the host activity
//mListener.onURLSelected(((TextView) view).getText().toString());
}
});
}
Thanks in advance.
Typically for long running operations in the background, like listening to a server, incoming messages, etc, you need to use Services. You do so by subclassing the Service class in Android.
Now for your problem - the design approach should be that you have a background service listening to incoming messages. Anytime a message is received (an input stream in your socket operator) you should send a "broadcast" an intent that a message was received. A custom broadcast receiver that you create should wait for this broadcast. Within the onReceive() method of this receiver, you should trigger the creation of the bundle and updating your message.
Remember you should always delegate your long running operations in Android to services. That is exactly what they are for.
So basically if you're already listening for new messages to come in your activity, then you must have some kind of callback like onMessageRecieved() or something like that.
If you do, you can then notify your fragment in this way.
Create a field (goes under your class declaration) called curFrag, so something like this:
public class MyActivity extends Activity {
private Fragment curFrag;
//other code...
}
then in the code you posted you would initialize the curFrag there, but you also need to set a tag for the current fragment. This will be based on your case statement. Make some final string variables as tags.
i.e.
public static final String CHATSTAG = "chatstag";
#Override
public void onNavigationDrawerItemSelected(int position) {
Bundle bundle = new Bundle();
bundle.putStringArrayList("contacts", arr);
bundle.putStringArrayList("messages", messages);
Fragment fragment = null;
String tag = null;
switch (position) {
case 0:
tag = FRIENDSTAG;
fragment = new FriendsFragment();
break;
case 1:
tag = CHATSTAG;... and so on through the switch statement.
fragment = new ChatsFragment();
break;
case 2:
fragment = new GroupsFragment();
break;
case 3:
fragment = new LogoutFragment();
break;
default:
break;
}
if (fragment != null) {
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
//remember to set the tag.
if(tag != null) {
fragmentManager.beginTransaction()
.replace(R.id.container, fragment, tag).addToBackStack(null).commit();
} else {
fragmentManager.beginTransaction()
.replace(R.id.container,fragment,DEFAULTTAG).addToBackStack(null).commit();
}
//new code
curFrag = fragment;
}
}
Now in your activity when a new message comes in, check the tag of the fragment and then if it matches a certain fragment, notify the fragment that new data has come in and retrieve it in the fragment.
public void onMessageRecieved() {
if(curFrag.getTag().equalsIgnoreCase(CHATSTAG)) {
ChatsFragment frag = (ChatsFragment) curFrag;
frag.notifyDataRecieved();
}
}
Once you have a reference to your fragment in the activity, you have access to any public methods in that fragment.
If your fragment cannot access the data on its own, then you'll need to get a reference to the activity and create a method in the activity that returns the new data.
So in your activity:
public String getMessageData() {
String newData = ...//get stuff from server;
return newData;
}
then in your fragment
public void notifyNewMessage() {
try {
MyActivity activity = (MyActivity) getActivity();
} catch (ClassCastException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
String message = activity.getMessageData();
//do something with the message.
}
It's not necessarily pretty but it works pretty well. You should also check to make sure your fragments are attached when you do this so that you avoid null exceptions.
Hope this helps!