I have a MasterActivity that has a few fragments. One fragment allows the user to open up Square to pay. After the user signs their name in Square and the data is returned to my app, my app crashes because the Payment fragment can't find the MasterActivity as it is null.
This only happens when the user signs the receipt. If the user pays cash (no signature) the My App works fine.
I have noticed that the when the Square App is ready for a signature it rotates the screen, just before the signature capture activity is view-able, I can see my app rotate too.
After the Square application has returned to my app, I can see the successful upload of the data to my server from my app. Then, it is only when the payment fragment asks the MasterActivity to refresh the data, I get a null pointer exception for the DISP_KEY in MasterAcitvity .
Can any see what I might be doing wrong?
MasterActivity
public class MasterActivity extends AppCompatActivity {
private String TAG = getClass().getSimpleName();
private String DISP_KEY = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_master);
Intent intent = getIntent();
DISP_KEY = (String) intent.getSerializableExtra("SELECTED_DISPATCH");
initView();
refreshData();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
public void refreshData() {
//Do some network download data stuff using the DISP_KEY
}
private void initView() {
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
//JUST TEXT
tabLayout.addTab(tabLayout.newTab().setText("Details"));
tabLayout.addTab(tabLayout.newTab().setText("Sections"));
tabLayout.addTab(tabLayout.newTab().setText("Area"));
tabLayout.addTab(tabLayout.newTab().setText("Notes"));
tabLayout.addTab(tabLayout.newTab().setText("Payments"));
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new TabPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
}
}
PaymentFragment
public class PaymentFragment extends Fragment {
private static final int SQUARE_CHARGE_REQUEST_CODE = 1;
private String TAG = getClass().getSimpleName();
private PosClient posClient;
public PaymentFragment() {
// Required empty public constructor for fragments
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_payment, container, false);
initGUI(view);
return view;
}
#Override
public void onStart() {
super.onStart();
mVehicle = ((MasterActivity) this.getActivity()).getCurrentVehicle();
if (mVehicle != null) {
reloadData();
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (this != null) {
((MasterActivity) context).registerDataReloadListener(this);
posClient = PosSdk.createClient(getActivity(), AppConfig.SQUARE_APP_ID);
} else {
((MasterActivity) context).onBackPressed();
}
}
#Override
public void onDetach() {
super.onDetach();
if (this != null) {
((MasterActivity) getActivity()).unregisterDataReloadListener(this);
}
}
public void reloadData() {
//Ask the master activity to reload data
}
// SQUARE
private void acceptSquarePayment() {
ChargeRequest.TenderType types;
ChargeRequest request = new ChargeRequest.Builder(Integer.parseInt(square_balance), CurrencyCode.USD)
.enforceBusinessLocation(square_location_id)
.restrictTendersTo(types)
.requestMetadata(square_call_num)
.autoReturn(3200, TimeUnit.MILLISECONDS)
.build();
Intent intent = posClient.createChargeIntent(request);
startActivityForResult(intent, SQUARE_CHARGE_REQUEST_CODE);
}
// GET SQAURE RESULTS
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
ChargeRequest.Success success = posClient.parseChargeSuccess(data);
sendReceiptToAPIServer(success.serverTransactionId, success.clientTransactionId, success.requestMetadata);
}
}
private void sendReceiptToAPIServer(String serverTransactionId, String clientTransactionId, String callNum) {
//Do some data upload stuff
//After the successufull upload, this is where the crash happens
reloadData();
}
#Override
public void onDataReload() {
mVehicle = ((MasterActivity) this.getActivity()).getCurrentVehicle();
if (getView() != null) {
reloadData();
}
}
}
Related
I'm changing old styled code for Activity Results, and got stuck on permission results. In fragment where users can pick one contact from a list and copy it's data, permission callback is not working at all, however activity result is firing callback... Here is simplified fragment class:
public class PeopleAddEdit_SubVen_Fragment extends Fragment {
private ActivityResultLauncher<Intent> mActivityResult;
private ActivityResultLauncher<String> mPermissionResult;
#Override
public View onCreateView(#NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_addedit_ppl_subven, container, false);
ImageView contacticon = view.findViewById(R.id.contacticon_container);
contacticon.setImageDrawable(AppLib.getAppDrawable(R.drawable.icons_88));
contacticon.setOnClickListener(view1 -> processContact());
return view;
}
#Override
public void onAttach(#NotNull Context context) {
super.onAttach(context);
AppCompatActivity activity = (AppCompatActivity) context;
mActivityResult = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
//processing data here
...
}
}
});
mPermissionResult = registerForActivityResult(
new ActivityResultContracts.RequestPermission(),
new ActivityResultCallback<Boolean>() {
#Override
public void onActivityResult(Boolean result) {
if (result) {
PeopleAddEdit_SubVen_Fragment.this.startProcessingContacts();
} else {
Toast.makeText(PeopleAddEdit_SubVen_Fragment.this.getActivity(), "No permission.", Toast.LENGTH_SHORT).show();
}
}
});
}
private void processContact() {
int getContacts = ContextCompat.checkSelfPermission(thisContext, Manifest.permission.READ_CONTACTS);
if (getContacts != PackageManager.PERMISSION_GRANTED) {
mPermissionResult.launch(Manifest.permission.READ_CONTACTS);
} else {
startProcessingContacts();
}
}
private void startProcessingContacts() {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
mActivityResult.launch(intent);
}
}
When Contacts are not granted, after displaying popup to deny or allow Contacts, nothing happens regardless of choice. If I click button again (after I allow Contacts), I get contacts displayed, so activity result is firing callback, but permission callback is not fired at all, but permission is granting or denying, depending on choice, but not firing result.
In the build.gradle I have
implementation 'androidx.activity:activity:1.4.0'
implementation 'androidx.fragment:fragment:1.4.0-rc01'
Any ideas why is not firing?
Problem solved. I just needed to remove from parent activity
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
...
}
and it works now.
I have a working AsyncTask to get data from a server and display it in a TextView. But is it possible to output the data into a TextView which is located in a fragment? So let's say, the AsyncTask is loaded in the MainActivity and the output will be in a fragment.
This is my AsyncTask:
private static class FtpDownload extends AsyncTask<String, String, String> {
private WeakReference<GuidanceActivity> activityWeakReference;
FtpDownload(GuidanceActivity activity) {
activityWeakReference = new WeakReference<>(activity);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... FTPconnection) {
GuidanceActivity activity = activityWeakReference.get();
if (activity == null || activity.isFinishing()) {
return null;
}
try {
FTPClient ftpClient = new FTPClient();
ftpClient.connect("", 21);
System.out.println(ftpClient.getReplyString());
ftpClient.enterLocalPassiveMode();
ftpClient.login("anonymous", "");
ftpClient.changeWorkingDirectory("/");
InputStream inStream = ftpClient.retrieveFileStream(".html");
activity.contents = IOUtils.toString(inStream, StandardCharsets.UTF_8);
System.out.println(activity.contents);
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String output) {
GuidanceActivity activity = activityWeakReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
TextView textView = activity.findViewById(R.id.text_view);
textView.setText(Html.fromHtml(activity.contents));
}
}
In your fragment:
public class MyFragment extends Fragment {
TextView myTextView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = View root = inflater.inflate(R.layout.my_frag_layout, null);
myTextView = (TextView) view.findViewById(R.id.myTextView);
//rest of your implementation of onCreateView
return view;
}
//this will be called from activity
public void updateTextView(String text) {
myTextView.setText(text);
}
}
in your activity:
public class MyActivity extends AppCompatActivity {
private final String FRAGMENT_TAG = "myFragment";
private static class FtpDownload extends AsyncTask<String, String, String> {
//rest of your FtpDownload class
#Override
protected void onPostExecute(String output) {
GuidanceActivity activity = activityWeakReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG );
/* or
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment );
if your fragment is in an xml layout */
fragment.updateTextView(Html.fromHtml(activity.contents));
}
}
}
Yes, it is possible. This is a sample for WiFi scanning from MainActivity and the results are show at fragment. I believe you can understand the logic and convert it for your project
MainActivity:
public class MainActivity extends AppCompatActivity implements FragmentDiscoverWiFi.ScanWiFi;
//public variable
FragmentDiscoverWiFi fragmentDiscoverWiFi;
//This will be called from your fragment
#Override
public void onScanWiFi(FragmentDiscoverWiFi fragment) {
fragmentDiscoverWiFi = fragment;
}
//use something like this when your want to update fragment
fragmentDiscoverWiFi.onScanWiFiComplete();
Fragment:
public class FragmentDiscoverWiFi extends Fragment {
private Context mContext;
public interface ScanWiFi {
public void onScanWiFi(FragmentDiscoverWiFi fragment);
}
public FragmentDiscoverWiFi() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
mContext = context;
super.onAttach(context);
}
public void onScanWiFiComplete() {
if (!isDetached()) {
//Access your data from MainActivity like this:
Log.d(TAG, "Total APs:" + ((MainActivity) mContext).wifiScanResults.size());
}
}
#Override
public void onResume() {
super.onResume();
if (!getUserVisibleHint()) {
return;
}
pullToRefreshText = rootView.findViewById(R.id.pullToRefreshText);
pullToRefresh = rootView.findViewById(R.id.pullToRefresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.d(TAG, "refreshing...");
pullToRefresh.setRefreshing(true);
((MainActivity)mContext).onScanWiFi(FragmentDiscoverWiFi.this);
}
});
}
}
I have an app consisting of (among other things) one Activity and one Fragment. In the Activity som data is displayed using TextViews, and in the Fragment the user can input some data using EditText-views. I have a method which takes data from both the Activity and Fragment, performs some calculations and finally displays a result in both the Fragment and the Activity. This method currently works when I call if after editing the text in any of the EditText-views in the Fragment. However, I also want to call it each time I update the data in the Activity but when I attempt this, I can not fetch the EditText data because they return null.
So my question is: what is good practice, or the ”right way” to do when dealing with methods that are supposed to be reached from both an Activity and a Fragment? I would greatly appreciate if someone could lead me onto the right track.
I have read the official documentation on Fragments and there ViewModel was mentioned. But this doesn’t seem suitable in for my application since I want the Activity to be involved. Do I need to use this or can I go through my main Activity? I’ve also read about Interfaces, but I’m not sure which one would suit my project best. I’m currently using Interfaces, but I’m not sure if I’m doing it correctly.
I’ve also watched this video and read these following questions:
Shared ViewModel to help communication between fragments and parent activity
Call a fragmentMethod from another fragment, but can't refer to them in parentFragmentActivity's View pager
how to manage the fragments in android correctly?
"My God"’s reply to this question was helpful but I’m still not sure what is the best thing to do in my case, as I have a Fragment where user can input data, and the same fragment should also view data as a result of that input. (Maybe my first mistake is building the app like this?)
I provide some code in case it is helpful.
public class AccuracyFragment extends Fragment {
EditText editTextLevel, editTextAccuracy;
private OnFragmentInteractionListener mListener;
public AccuracyFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_accuracy, container, false);
editTextAccuracy = view.findViewById(R.id.text_accuracy_character);
editTextLevel = view.findViewById(R.id.text_level_character);
TextWatcher watcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//Doing nothing
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//Doing nothing
}
#Override
public void afterTextChanged(Editable editable) {
updateFragment(Float.valueOf(editTextLevel.getText().toString()), Float.valueOf(editTextAccuracy.getText().toString()));
}
};
editTextLevel.addTextChangedListener(watcher);
editTextAccuracy.addTextChangedListener(watcher);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null; //I don’t know what this does
}
#Override
public void onResume() {
super.onResume();
// updateFragment(); //Should I have this?
}
public interface OnFragmentInteractionListener {
String[] onAccuracyFragmentInputChanged(float levelFromFragment, float accuracyFromFragment); }
public void updateFragment(float level, float accuracy) {
//Complicated method doing things with editTextLevel and editTextAccuracy. However, it doesn’t work when this method is called from outside AccuracyFragment – EditTexts are null
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onStop() {
super.onStop();
}
}
public class MainActivity extends AppCompatActivity implements AccuracyFragment.OnFragmentInteractionListener, AdapterView.OnItemSelectedListener {
AccuracyFragment accuracyFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_new);
selectedID = null;
textView1 = (TextView) findViewById(R.id.text_1);
textView2 = (TextView) findViewById(R.id.text_2);
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state, then we don't need to do anything and should return or else we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create a new Fragment to be placed in the activity layout
accuracyFragment = new AccuracyFragment();
}
}
//This is the core method which takes the value from two EditTexts in the Fragment, and two TextViews in the MainActivity
private String[] getRequiredAccuracy(float firstValueFromActivity, float secondValueFromActivity, float firstValueFromFragment, float secondValueFromFragment) {
//This methods uses parameters from the Activity, and two from the Fragment, and is intended to be called from both the Activity and from the Fragment itself
String returnValues[] = {s, q, r, c}; //This method is too complex to show, but it will end up outputting some values
return returnValues;
}
public void methodCalledUponClick(View view) {
//After showing a Dialog with some choices, I intend to call the method from fragment:
accuracyFragment.updateFragment();
}
#Override
public String[] onAccuracyFragmentInputChanged(float levelFromFragment, float accuracyFromFragment) {
String returnValues[] = {"0", "0", "0"};
if (selectedID != null) {
if (textView1.length() == 0 || textView2.length() == 0) {
//Do nothing if any of these are empty
} else {
returnValues = getRequiredAccuracy(Float.valueOf(textView1.getText().toString()), Float.valueOf(textView2.getText().toString()), levelFromFragment, accuracyFromFragment);
}
}
return returnValues;
}
}
}
You can go ahead with callback/Interface to communicate with fragment and activity simultaneously.
For Creating callback/Interface:
public interface CallBackListener {
void onCallBack(String value);// pass any parameter in your onCallBack which you want to return
}
In Fragment Class:
public class AccuracyFragment extends Fragment {
private CallBackListener callBackListener;
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//getActivity() is fully created in onActivityCreated and instanceOf differentiate it between different Activities
if (getActivity() instanceof CallBackListener)
callBackListener = (CallBackListener) getActivity();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
EditText editText = (EditText) view.findViewById(R.id.edittext);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(callBackListener != null)
callBackListener.onCallBack(s.toString());
}
});
}
}
In your Activity:
public class MainActivity extends AppCompatActivity implements CallBackListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onCallBack(String value) {
Toast.makeText(mContext,"onCallback Called",Toast.LENGTH_LONG).show();
}
}
My app currently looks like this:
I want to add a search bar where I can search any place as Google maps. The search bar should be in an Auto Complete way.I got this code from https://examples.javacodegeeks.com/android/android-google-places-autocomplete-api-example/
Have a look at the above link.
And these codes where for an ORDINARY APP to get Auto Complete search bar. It doesnt suit for app using fragment. And I dont know how to do it with fragments.
Here is my code
For the Main Activity (ProfileActivity)
public class ProfileActivity extends AppCompatActivity {
final String TAG = this.getClass().getName();
BottomBar mBottomBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mBottomBar = BottomBar.attach(this, savedInstanceState);
mBottomBar.setItemsFromMenu(R.menu.menu_user, new OnMenuTabClickListener() {
#Override
public void onMenuTabSelected(#IdRes int i) {
if(i == R.id.ButtonBarFeed)
{
NewsFragment f = new NewsFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
else if(i == R.id.ButtonBarMap)
{
MapFragment f = new MapFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
else if(i == R.id.ButtonBarUser)
{
UserFragment f = new UserFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,f).commit();
}
}
#Override
public void onMenuTabReSelected(#IdRes int menuItemId) {
}
});
mBottomBar.mapColorForTab(0,"#28809f");
}
public boolean googleServicesAvailable(){
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvailable = api.isGooglePlayServicesAvailable(this);
if(isAvailable == ConnectionResult.SUCCESS){
return true;
}else if(api.isUserResolvableError(isAvailable)){
Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
dialog.show();
} else {
Toast.makeText(this,"Can't connet to Play Services", Toast.LENGTH_LONG).show();
}
return false;
}
boolean twice;
#Override
public void onBackPressed() {
Log.d(TAG, "click");
if(twice == true){
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
twice = true;
Log.d(TAG, "twice:" + twice);
Toast.makeText(ProfileActivity.this, "Please press BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice = false;
Log.d(TAG, "twice:" + twice);
}
}, 3000);
}
}
MapFragment
public class MapFragment extends Fragment implements OnMapReadyCallback {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.map, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment fragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.mapView1);
fragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap){
}
}
I have to add a search bar with Auto Complete like Google map.Please with reference of the Link which I have given at starting, Can Anyone code for my MapFragment?
I have two classes that is for Facebook login, and it works.
I can press the Loginbutton, write in my username/password and it will log me in, BUT the thing is that I will come back to the Main-class (startsite) with my logo picture and so on.
What I want to do is, when you pressed the loginbutton and logged in, you will be redirected to a new Activity
Here is my 2 Classes you can see, but where do I do the redirect?
Read on StackOverflow about the "onComplete" but I cant make it, think its because I use SDK 3.5.2 and not 2.0. So How can i make a redirect to a new Activity after success login.
My MainActivity:
public class SocialLoginActivity extends FragmentActivity {
private SocialLoginFragment socialLoginFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
socialLoginFragment = new SocialLoginFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, socialLoginFragment).commit();
} else {
// Or set the fragment from restored state info
socialLoginFragment = (SocialLoginFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
}
And here is the FragmentClass:
public class SocialLoginFragment extends Fragment {
private static final String TAG = "SocialLoginFragment";
private UiLifecycleHelper uiHelper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_social_login, container,
false);
LoginButton authButton = (LoginButton) view
.findViewById(R.id.authButton);
authButton.setFragment(this);
// authButton.setReadPermissions(Arrays.asList("name", "user_birthday",
// "friends_birthday"));
return view;
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onResume() {
super.onResume();
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
}
EDIT
The error you see is because a Fragment is not a Context object. You need to get the parent activity, something like:
Intent intent = new Intent(getActivity(), MainActivity.class);