Show Toast message even after Fragment has been detached? - android

My app uses a Navigation Drawer with several menu items which basically opens different Fragments. Each fragments may run an AsyncTask that shows Toast message afterwards. However, when the user tries to open a fragment while another fragment is running, I get a nullpointer error which is understandable since the original fragment has been detached.
However, is it possible to have the Toast show even then? I basically has this code when an item is clicked on the navigator.
public void setFragment(Fragment fragment) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, fragment)
.commit();
}
Then on the fragment is just a simple asynctask that shows a Toast message onPostExecute.
Toast.makeText(getContext(), t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
Appreciate any help.
UPDATE (03/28/2018)
I tried using listener and it seems to work.
I basically have a BaseFragment in which all my fragments extends. I just added a callback in it.
public class BaseFragment extends Fragment {
private OnToast callback;
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
callback = (BaseFragment.OnToast) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement OnAuthenticateListener");
}
}
public OnToast getCallback() {
return callback;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
}
public interface OnToast {
void toast(String message);
}
}
In my actual fragment, I have:
public class JailsFragment extends BaseFragment {
private List<Jail> jailList = new ArrayList<>();
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setTitle("Jails");
setAdapter(new JailAdapter());
if (savedInstanceState == null) {
onSwipeRefresh();
}
}
#Override
public void onSwipeRefresh() {
super.onSwipeRefresh();
setRefreshing(true);
jailList.clear();
FreeNAS.getInstance().getJails().getJails(new Callback<List<Jail>>() {
#Override
public void onResponse(Call<List<Jail>> call, Response<List<Jail>> response) {
if (response.code() == 200) {
jailList.addAll(response.body());
notifyDatasetChanged();
} else {
//Toast.makeText(getContext(), response.message(), Toast.LENGTH_LONG).show();
getCallback().toast(response.message());
}
setRefreshing(false);
}
#Override
public void onFailure(Call<List<Jail>> call, Throwable t) {
//Toast.makeText(getContext(), t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
getCallback().toast(t.getLocalizedMessage());
setRefreshing(false);
}
});
}
}
Then in my MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, BaseFragment.OnToast {
private SharedPreferences pref;
private Toolbar toolbar;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
private NavigationView navigationView;
#Override
public void toast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = PreferenceManager.getDefaultSharedPreferences(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
setFragment(new AuthenticateFragment());
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
final int id = item.getItemId();
drawer.closeDrawer(GravityCompat.START);
drawer.postDelayed(new Runnable() {
#Override
public void run() {
if (id == R.id.nav_plugins) {
setFragment(new PluginsFragment());
} else if (id == R.id.nav_jails) {
setFragment(new JailsFragment());
} else if (id == R.id.nav_jails_configuration) {
setFragment(new ConfigurationFragment());
} else if (id == R.id.nav_services) {
setFragment(new ServicesFragment());
} else if (id == R.id.nav_alerts) {
setFragment(new AlertsFragment());
} else if (id == R.id.nav_updates) {
setFragment(new UpdatesFragment());
}
}
}, 300);
return true;
}
public void setFragment(Fragment fragment) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, fragment)
.commit();
}
}

I assume you are receiving a nullPointer exception here
Toast.makeText(getContext(), t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
I would say that you are receiving the null pointer because you do not have the context anymore.
The possible solution is:
1- Declare you Application as singleton, then you could use MyApplication.getInstance() and use this as a context for the Toast message. Check this link to see how to create this singleton. Also it is recommended to use the applicationContext instead of the activity for toast messages
As far as I understand getContext() and getActivity() will return the same object, which is the activity so that will not help.
EDIT 1:
The problem with the solution you are proposing (having a reference to the Activity, in this case as an interface) is that you may have memory leaks. When I say "may have" is because you are doing something special when you put this line:
setRetainInstance(true);
You may want to read this post.
The memory leak will be generated when you do not need the Activity anymore (let's say you move to another activity) but the fragment (the object) is not being destroyed yet for some reason. Another example is with a low connection to Internet, then the user may leave the screen to move to another one, but your fragment is still alive and so your activity can not be garbage collected. This is why I do not recommend your approach :).
PS: sorry for the late answer, I was on vacation :P.

Related

What's the best way to open the last displayed fragment upon reopening the app?

I am using drawerlayout to allow the user to open different questionnaires. The questions in the questionnaire are different fragments. The problem is that when a questionnaire is started and say the use goes to question no. 5 and exits the app then she or he will have to start from the home page ie first fragment in the drawer layout. How do I save the last fragment ie question shown so that I can show it again when the app is reopened?
Below is the code in one of the fragments that do not open up if the user taps the Home button.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { \\ handle view related code and triggering other functions }
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
cardContext = context;
if (context instanceof OnShoppingDoneListener) {
onShoppingDoneListener = (OnShoppingDoneListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onResume() {
super.onResume();
bundle = getArguments();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onDetach() {
super.onDetach();
onShoppingDoneListener = null;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("cartContent", selectionItemArrayList);
}
And here is the relevant code Main Activity where I open that particular fragment:
public class MainActivity extends AppCompatActivity implements
OnRestaurantSelect {
public void onRestaurantSelect(Bundle bundle){
boolean direction = bundle.getBoolean("direction");
if (direction) {
MenuCardFragment fragment = new MenuCardFragment();
openFragment(bundle, fragment, true);
} else {
AddressFragment fragment = new AddressFragment();
openFragment(bundle, fragment, false);
}
}
private void openFragment(Bundle bundle, Fragment fragment, Boolean direction) {
// Passing the pickup or delivery option + address + schedule + restaurant + order details + payment
fragment.setArguments(bundle);
//Starting fragment with animation
if (direction) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_right).replace(R.id.frame_container, fragment, null);
fragmentTransaction.commit();
} else {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_left).replace(R.id.frame_container, fragment, null);
fragmentTransaction.commit();
}
}
Design a key for each fragment, when the app exits, save that key in a SharedPreference, than when the app restart, get that SharedP and open that fragment

Can not perform this action after onSaveInstanceState - android

I have an authorization app. In that app user have accessToken and refreshToken. I done something like this, that if user login on other hardware than in real hardware he logs out automatically. Imagine I have phone1 where I logged in. And now I'm logging in phone2. When I authorize my tokens changes. So I check in phone1 if tokens are changed than logout automatically. But sometimes after that logout I'm getting error like this Exception :
java.lang.IllegalStateException: Can not perform this action after
onSaveInstanceState.
Here is where I'm log out when tokens are expired.
Note that is a
Call<RefreshTokenActivation> newToken = apiClient.newToken(supportObjToken);
newToken.enqueue(new Callback<RefreshTokenActivation>() {
#Override
public void onResponse(Call<RefreshTokenActivation> call, Response<RefreshTokenActivation> response) {
if (response.isSuccessful()) {
} else {
if (response.code() == 401) {
//Perform this call if refresh token is expired
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Activity activity = (Activity) context;
MainActivity mainActivity = (MainActivity) activity;
mainActivity.logOut();
}
}, 1000);
}
}
}
If response is 401, that means that my tokens are expired.If tokens are expired, after a second I throw my user to mainActivity.
Here is the code in MainActivity :
public class MainActivity extends AppCompatActivity
implements FragmentChangeListener, TabLayoutLocationInterface {
private ConnectionDetector connectionDetector;
private SlidePageTabsMainFragment slidePageTabsMainFragment;
private MainFragment mainFragment;
private RelativeLayout logOut;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferencesManager.init(this);
setContentView(R.layout.activity_main);
logOut = (RelativeLayout) findViewById(R.id.list6);
connectionDetector = new ConnectionDetector(this);
slidePageTabsMainFragment = new SlidePageTabsMainFragment();
mainFragment = new MainFragment();
connectionEnable();
userLogOut();
}
public void connectionEnable() {
if (!connectionDetector.isConnected()) {
Toast.makeText(this, "Please check your Internet", Toast.LENGTH_LONG).show();
} else {
Boolean loggedIn = SharedPreferencesManager.getInstance().getUserLogged();
if (loggedIn) {
this.replaceFragment(slidePageTabsMainFragment, true);
} else {
this.replaceFragment(mainFragment, true);
}
}
}
#Override
public void replaceFragment(BaseFragment fragment, Boolean isAddToBackStack) {
String backStateName = fragment.getFragmentName();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.main_fragment_container, fragment, backStateName);
transaction.addToBackStack(backStateName);
transaction.commit();
}
#Override
public int getTabLayoutLocation() {
SlidePageTabsMainFragment slidePageTabsMainFragment = (SlidePageTabsMainFragment)
getSupportFragmentManager().findFragmentByTag("SlidePageTabsMainFragment");
if (slidePageTabsMainFragment == null) {
return 0;
}
return slidePageTabsMainFragment.getTabLayoutLocation();
}
//If user click logOut button
public void userLogOut() {
logOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferencesManager.getInstance().setUserLogin(false);
SharedPreferencesManager.getInstance().removeUser();
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
replaceFragment(mainFragment, false);
}
});
}
//A function for automatic logOut
public void logOut() {
SharedPreferencesManager.getInstance().setUserLogin(false);
replaceFragment(new MainFragment(), false);
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
recreate();
SharedPreferencesManager.getInstance().removeUser();
}
#Override
protected void onResume() {
super.onResume();
Log.d("Test", "Text");
}
}
I think there is no something hard. So I getting this exception in transaction.commit();
line in replaceFragment() method in MainActivity. In that call you see I'm calling mainActivity.logOut(); and you see in MainActivity the logOut function.
//A function for automatic logOut
public void logOut() {
SharedPreferencesManager.getInstance().setUserLogin(false);
replaceFragment(new MainFragment(), false);
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
recreate();
}
So in this method I change the SharedPreferences value (that I need for checking on application open does user logged in or not?). After that I'm replacing fragment into mainFragment(that's the base fragment and yes I working on fragments). After that I pop all fragments because after logout if I will click back button, it will go back, so after popping I recreate the app. After recreates it feels like app opened first time. Ok so why it throws exception like this? Any idea?
Used transaction.commitAllowingStateLoss(); instead of transaction.commit();
If you do this than your final state in not allow saved but it is ok if you don't care
For more clarification about commit() and commitAllowingStateLoss() read this blog.

Android fragment lifecycle issue with actionbar

I want to realize the navigation of the fragments using the following code:
public abstract class BaseFragment extends Fragment {
private static String TAG = "BaseFragment";
private BaseFragmentActions baseFragmentActions;
#Override
public void onAttach(Context context) {
super.onAttach(context);
Activity activity = null;
if (context instanceof Activity){
activity = (Activity) context;
}
Log.i(TAG, "onAttach = ");
try {
baseFragmentActions = (BaseFragmentActions)activity;
} catch (ClassCastException e) {
}
Log.i("onAttach",""+(getBackStackCount()!=0));
baseFragmentActions.resetToolbarNavigation(getBackStackCount()!=0);
}
#Override
public void onDetach() {
super.onDetach();
Log.i("BaseFragment", "onDestroy = " + (getBackStackCount() - 1));
baseFragmentActions.resetToolbarNavigation((getBackStackCount() - 1) != 0);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private int getBackStackCount() {
int b = getActivity().getSupportFragmentManager().getBackStackEntryCount();
Log.i("getBackStackEntryCount", "====== "+b);
return b;
}
public interface BaseFragmentActions {
public void resetToolbarNavigation(boolean backNavigationEnabled);
}
}
All my fragments extend this Base Activity. And inside my main activity i implement BaseFragmentActions, and implemented this method:
#Override
public void resetToolbarNavigation(boolean backNavigationEnabled) {
Log.i("BaseActivity", "reset " + backNavigationEnabled);
getSupportActionBar().setDisplayHomeAsUpEnabled(backNavigationEnabled);
if (backNavigationEnabled) {
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("resetToolbarNavigation", "setNavigationOnClickListener");
onBackPressed();
}
});
} else {
initNavigation();
syncState();
}
}
Everything works fine but when I change the screen orientation we obtain error that getSupportActionBar = null.
This is because of what I call going to attach. How can I fix this error? I tried to make checking whether getSupportActionBar is not zero. I'm not getting an error, but "up" Arrow replaced hamburger...
Advise what you can do in this case. Also share links to navigate the implementation of such fragments. Sorry if something wrong written, or I made a grammatical error)).
Hi sorry for the delay in the answer, the problem you're having is because when onAttach is called the getSupportActionBar() is not set yet, instead you need to make sure the Activity is already created when interacting with Activity components, so just put your call inside the onActivityCreated method of your Fragment like this:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
baseFragmentActions.resetToolbarNavigation(getBackStackCount()!=0);
}

GoogleApiClient not connected if used from fragment

I discovered a strange behaviour today.
I have my activity which connects to the GoogleApiClient in onStart() and disconnects in the onStop()
The activity uses a GridViewPager to show my fragments. To send messages through the Data Layer i use a callback interface between activity and fragment.
If i call sendMessage() from a button within the Activity layout it works fine. If sendMessage() is executed by the fragment using the callback interface sendMessage() shows the "not connected" Toast.
In both ways the same method in the Activity is called so how is it possible that it behaves different ?
I should mention that the problem only occours after the application is restarted for the first time.
Activity
public class WearPlex extends WearableActivity implements
NavigationRemoteCallbacks,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private List<Node> nodeList = new ArrayList<Node>();
private List<Fragment> fragmentList = new ArrayList<Fragment>();
private GoogleApiClient googleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wear_plex);
setAmbientEnabled();
fragmentList.add(NavigationRemoteFragment.getInstance(this));
GridViewPager mGridPager = (GridViewPager)findViewById(R.id.gridViewPager);
mGridPager.setAdapter(new MainGridPageAdapter(getFragmentManager(), fragmentList));
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
nodeList.clear();
Wearable.NodeApi.getConnectedNodes(googleApiClient).setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult nodes) {
for (Node node : nodes.getNodes()) nodeList.add(node);
}
});
}
#Override
public void navigationRemoteSendCommand(String commandPath) {
sendMessage(commandPath, null);
}
public void debugOnClick(View view) {
sendMessage("/debug", null);
}
public void sendMessage(String path, byte[] data) {
if (googleApiClient.isConnected()) {
for (int i = 0; i < nodeList.size(); i++) {
if (nodeList.get(i).isNearby()) {
Toast.makeText(this, "Send message", Toast.LENGTH_SHORT).show();
Wearable.MessageApi.sendMessage(googleApiClient, nodeList.get(i).getId(), path, data);
}
}
} else {
Toast.makeText(this, "Not connected", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this, "Connection failed", Toast.LENGTH_SHORT).show();
}
Fragment
public class NavigationRemoteFragment extends Fragment {
private static NavigationRemoteFragment navigationRemoteFragment = null;
private NavigationRemoteCallbacks callbackHandler = null;
private ImageButton navBtnCenter;
public static NavigationRemoteFragment getInstance(NavigationRemoteCallbacks handler) {
if (navigationRemoteFragment == null) {
navigationRemoteFragment = new NavigationRemoteFragment();
navigationRemoteFragment.callbackHandler = handler;
}
return navigationRemoteFragment;
}
public NavigationRemoteFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_navigation_remote, container, false);
navBtnCenter = (ImageButton)v.findViewById(R.id.navBtnCenter);
navBtnCenter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callbackHandler.navigationRemoteSendCommand("/debug");
}
});
return v;
}
}
Callback interface
public interface NavigationRemoteCallbacks {
public void navigationRemoteSendCommand(String commandPath);
}
EDIT 1 code for MainGridPageAdapter
public class MainGridPageAdapter extends FragmentGridPagerAdapter {
private List<Fragment> fragmentList = null;
public MainGridPageAdapter(FragmentManager fm, List<Fragment> fragmentList) {
super(fm);
this.fragmentList = fragmentList;
}
#Override
public Fragment getFragment(int i, int i1) {
if (i1 < fragmentList.size()) return fragmentList.get(i1);
return null;
}
#Override
public int getRowCount() {
return 1;
}
#Override
public int getColumnCount(int i) {
return fragmentList.size();
}
You don't show the code for MainGridPageAdapter so I don't know how it is managing fragments. You mention that the problem occurs after a restart. Looking at the code in WearPlex.onCreate(), I suspect that the problem is caused fragments that are holding a reference to an old, destroyed instance of the activity.
A poorly documented behavior of FragmentManager is that it saves its state across restarts. This is often overlooked, resulting in duplicate fragment instances after a restart. The correct pattern for managing fragment creation in the onCreate() method of the host activity is:
if (savedInstanceState == null) {
// Not a restart
// Create a new instance of the fragment
// Add it to the fragment manager
} else {
// Restart
// The fragment manager has saved and restored the fragment instances
// Use findFragmentById() to get the fragment if you need it
}
You are not using savedInstanceState in onCreate() to test for restart. Are you seeing more fragments than you expect after restart? If so, the original fragments are holding a reference to the old activity, which was stopped, and has a disconnected GoogleApiClient. If the NavBtn of one of those fragments is clicked, you will see the "not connected" toast.
Update
The problem is caused by the way you are creating new instances of NavigationRemoteFragment, specifically the use of static member navigationRemoteFragment. After a restart, when the activity is recreated, the code calls NavigationRemoteFragment.getInstance(this). getInstance() finds navigationRemoteFragment not null because it is static, and does not create a new fragment. The fragment returned is the old one, which holds a reference to the old activity, which has been stopped and has a disconnected GoogleApiClient.
This could be confirmed by using the isDestroyed method and adding a some debug logging:
#Override
public void navigationRemoteSendCommand(String commandPath) {
if (isDestroyed()) {
Log.w("TEST", "This is an old instance of the activity");
}
sendMessage(commandPath, null);
}

Facebook FriendPickerFragment showing no friends

Any idea why the list might be empty?
The code is below.
public class PickFBFriendsActivity extends FragmentActivity {
FriendPickerFragment friendPickerFragment;
// A helper to simplify life for callers who want to populate a Bundle with the necessary
// parameters. A more sophisticated Activity might define its own set of parameters; our needs
// are simple, so we just populate what we want to pass to the FriendPickerFragment.
public static void populateParameters(Intent intent, String userId, boolean multiSelect, boolean showTitleBar) {
intent.putExtra(FriendPickerFragment.USER_ID_BUNDLE_KEY, userId);
intent.putExtra(FriendPickerFragment.MULTI_SELECT_BUNDLE_KEY, multiSelect);
intent.putExtra(FriendPickerFragment.SHOW_TITLE_BAR_BUNDLE_KEY, showTitleBar);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pick_friends_activity);
FragmentManager fm = getSupportFragmentManager();
if (savedInstanceState == null) {
// First time through, we create our fragment programmatically.
final Bundle args = getIntent().getExtras();
friendPickerFragment = new FriendPickerFragment(args);
friendPickerFragment.setUserId(null);
fm.beginTransaction()
.add(R.id.friend_picker_fragment, friendPickerFragment)
.commit();
} else {
// Subsequent times, our fragment is recreated by the framework and already has saved and
// restored its state, so we don't need to specify args again. (In fact, this might be
// incorrect if the fragment was modified programmatically since it was created.)
friendPickerFragment = (FriendPickerFragment) fm.findFragmentById(R.id.friend_picker_fragment);
}
friendPickerFragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> fragment, FacebookException error) {
PickFBFriendsActivity.this.onError(error);
}
});
friendPickerFragment.setOnDoneButtonClickedListener(new PickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> fragment) {
setResult(RESULT_OK, null);
finish();
}
});
}
private void onError(Exception error) {
String text = getString(R.string.exception, error.getMessage());
Toast toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
toast.show();
}
#Override
protected void onStart() {
super.onStart();
}
}
Note that it's pretty much the same as the sample one.
Figured it out: my onStart() method was incomplete, missing the following line:
friendPickerFragment.loadData(false);
Must have deleted it accidently.

Categories

Resources