How to use onActivityResult() in fragment? - java

In my application i want use InAppBillling for buy some features !
I write payment methods into fragment but after show payment dialog and pay by user not show me any data into onActivityResult!
I write log.e into onActivityResult, but again not show.
I think not going into onActivityResult!
My fragment codes :
public class ServicesFragment extends BaseFragment implements IabHelper.OnIabSetupFinishedListener,
IabHelper.QueryInventoryFinishedListener, IabHelper.OnIabPurchaseFinishedListener, IabHelper.OnConsumeFinishedListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_services, container, false);
...
}
#Override
public void onIabSetupFinished(IabResult result) {
if (iabHelper != null) {
iabHelper.flagEndAsync();
//This is call for payment
iabHelper.queryInventoryAsync(ServicesFragment.this);
}
}
#Override
public void onIabPurchaseFinished(IabResult result, final Purchase info) {
//After payment call this
if (result.isSuccess() && info != null) {
handler.post(new Runnable() {
#Override
public void run() {
getCheckBuyFromBazaar(jwtToken, packageName, productId, purchaseToken, buyID, 0, info);
}
});
}
}
#Override
public void onQueryInventoryFinished(IabResult result, Inventory inv) {
if (result.isSuccess()) {
bazaarProgressDialog.dismiss();
//Run bazaar dialog
if (iabHelper != null) {
iabHelper.flagEndAsync();
iabHelper.launchPurchaseFlow(activity, bazaarSKU, bazaarRequestCode,
ServicesFragment.this, bazaarHashCode);
}
}
}
#Override
public void onConsumeFinished(Purchase purchase, IabResult result) {
if (result.isSuccess() && purchase != null) {
if (purchase.getSku().equalsIgnoreCase(bazaarSKU)) {
//When purchase consumed
finishPage();
loadingProgressDialog.dismiss();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("BazaarPaymentLog", "Result");
if (iabHelper == null) return;
if (requestCode == bazaarRequestCode) {
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
if (resultCode == RESULT_OK) {
try {
JSONObject jo = new JSONObject(purchaseData);
purchaseToken = jo.getString("purchaseToken");
productId = jo.getString("productId");
packageName = jo.getString("packageName");
Log.e("BazaarPaymentLog", "purchaseToken : " + purchaseToken);
if (iabHelper != null) {
iabHelper.handleActivityResult(requestCode, resultCode, data);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
Show me payment dialog and i pay it, but after not going to onActivityResult!
I write above code into activity it's ok and run onActivityResult but into fragment not going into onActivityResult!
How can i fix it?

Actually the result is passed to Activity's onActivtyResult in order to get in Fragment's method you need to pass reult fron Activity to Fragment like below
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame);
fragment.onActivityResult(requestCode, resultCode, data);
}
and in Fragment call it same as you are calling currently
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
If you are using ViewPager you can get Fragment like below
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment mFragment = myPagerAdapter.getItem(mViewPager.getCurrentItem());
if (fragment instanceof ServiccesFragment){
((ServiccesFragment)fragment).onActivityResult(requestCode, resultCode, data);
}
}

Related

OnActivityResult does not work inside fragment. How can I fix this on my code?

So I am coding this app that needs to pick a profile picture from the phone, crop, compress and save the picture to a custom location in the internal memory and also set the compressed bitmap as a preview in a circular imageview. All this inside a fragment. But my onActivityResult is not called at all inside the fragment.
Here is my code:
ViewPagerAdapter.class
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new ConfigurationFragment1();
case 1:
return new ConfigurationFragment2();
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
ConfigurationFragment2.class
public class ConfigurationFragment2 extends Fragment {
CircularImageView profilePicker;
EditText user1NameInput;
Uri profileImageURI;
Bitmap compressedImageFile;
Boolean profileImageSet = false;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_configuration_2, container, false);
profilePicker = rootView.findViewById(R.id.configuration_profile_picker);
user1NameInput = rootView.findViewById(R.id.configuration_name_1);
profilePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
else if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
else {
chooseProfilePicture();
}
}
});
return rootView;
}
public void chooseProfilePicture(){
CropImage.activity().setGuidelines(CropImageView.Guidelines.ON).setAspectRatio(1,1).start(getActivity());
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == Activity.RESULT_OK)
{
assert result != null;
profileImageURI = result.getUri();
File thumbnailURI = new File(Objects.requireNonNull(profileImageURI.getPath()));
try
{
compressedImageFile = new Compressor(getActivity())
.setMaxHeight(500)
.setMaxWidth(500)
.setQuality(100)
.compressToBitmap(thumbnailURI);
}
catch (IOException e)
{
e.printStackTrace();
}
profilePicker.setImageBitmap(compressedImageFile);
String profilePictureFolder = "/com.testapp.app/";
String profilePictureUser1Name = "profilePicUser1.jpg";
String profilePictureUser1Path = Environment.getExternalStorageDirectory().toString() + profilePictureFolder + profilePictureUser1Name;
File imagePath = new File(profilePictureUser1Path);
FileOutputStream fos;
try {
if (!imagePath.exists()) {
File wallpaperDirectory = new File(Environment.getExternalStorageDirectory().toString() + profilePictureFolder);
wallpaperDirectory.mkdirs();
}
File file = new File(new File(Environment.getExternalStorageDirectory().toString() + profilePictureFolder), profilePictureUser1Name);
if (file.exists()) {
file.delete();
}
fos = new FileOutputStream(imagePath);
compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 85, fos);
fos.flush();
fos.close();
profileImageSet = true;
} catch (FileNotFoundException e) {
Log.e("eRROR", e.getMessage(), e);
} catch (IOException e) {
e.printStackTrace();
}
}
else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
{
assert result != null;
Exception error = result.getError();
}
}
}
}
and MainActivity.class
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configuration);
setTheme(R.style.AppThemeBlueStatusDarkText);
objectInstance();
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(viewPagerAdapter);
viewPager.setSwipeable(false);
viewPager.setCurrentItem(currentPage);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
The onActivityResult code works flawlessly in a normal activity, but not in this fragment. How exactly can I solve my issue? Thank you!
I believe the problem is here:
public void chooseProfilePicture(){
CropImage.activity().setGuidelines(CropImageView.Guidelines.ON).setAspectRatio(1,1).start(getActivity());
}
The source code for this library shows the following:
public void start(#NonNull Activity activity) {
mOptions.validate();
activity.startActivityForResult(getIntent(activity), CROP_IMAGE_ACTIVITY_REQUEST_CODE);
}
This means that the Activity argument to the start() method is going to be used to start the CropImage activity, and therefore will be the place that receives the result. Instead, you should use this other start() method that the library exposes:
public void start(#NonNull Context context, #NonNull Fragment fragment) {
fragment.startActivityForResult(getIntent(context), CROP_IMAGE_ACTIVITY_REQUEST_CODE);
}
That means that you'd use this code:
public void chooseProfilePicture(){
CropImage.activity().setGuidelines(CropImageView.Guidelines.ON).setAspectRatio(1,1).start(getActivity(), this);
}
And now the result should be delivered to your Fragment.
firstly you need to add tag to fragment ConfigurationFragment2 when initilaize it the edit onActivityResult in your activity like this :
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configuration);
setTheme(R.style.AppThemeBlueStatusDarkText);
objectInstance();
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(viewPagerAdapter);
viewPager.setSwipeable(false);
viewPager.setCurrentItem(currentPage);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment ConfigurationFragment2 = getSupportFragmentManager().findFragmentByTag("ConfigurationFragment2 Tag");
switch (requestCode) {
case CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE:
if (ConfigurationFragment2 != null)
ConfigurationFragment2.onActivityResult(requestCode, resultCode, data);
break;
}
}

Getting error Failed to load image while working with android vision api for scanning qr code

I am using the following code to scan the QR code and show it.
Main Activity
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bg1);
scan =(Button) findViewById(R.id.scanner);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isGooglePlayUpdated=isGooglePlayServicesAvailable(BG1.this);
if (isGooglePlayUpdated){
ActivityCompat.requestPermissions(BG1.this, new
String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
}
else
Toast.makeText(BG1.this,"Please update Google Play Services",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_WRITE_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
takePicture();
} else {
Toast.makeText(BG1.this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
}
private void takePicture() {
Intent intent = new Intent(BG1.this,scanActivity.class);
startActivityForResult(intent, PHOTO_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHOTO_REQUEST) {
if (resultCode == RESULT_OK){
if (data!=null){
String qrCode = data.getParcelableExtra(scanActivity.BarcodeObject);
Toast.makeText(BG1.this,qrCode,Toast.LENGTH_LONG).show();
Log.d(TAG, "Barcode read: " + qrCode);
}else {
Toast.makeText(BG1.this,"intent data is null",Toast.LENGTH_LONG).show();
Log.d(TAG, "No barcode captured, intent data is null");
}
}
else {
Toast.makeText(BG1.this,"Result code error ",Toast.LENGTH_LONG).show();
Log.d(TAG, "Result code error");
}
}
else {
}
}
scanActivity.java
public class scanActivity extends AppCompatActivity {
private static String TAG="scan Activity";
SurfaceView cameraView;
BarcodeDetector barcodeDetector;
CameraSource cameraSource;
SurfaceHolder holder;
public static final String BarcodeObject = "Barcode";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scan_activity);
cameraView=(SurfaceView) findViewById(R.id.camera_view);
cameraView.setZOrderMediaOverlay(true);
holder=cameraView.getHolder();
barcodeDetector=new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
if (!barcodeDetector.isOperational()){
Toast.makeText(this,"Sorry Can't setup",Toast.LENGTH_LONG).show();
// Check for low storage. If there is low storage, the native library will not be
// downloaded, so detection will not become operational.
IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
boolean hasLowStorage = registerReceiver(null, lowstorageFilter) != null;
if (hasLowStorage) {
Toast.makeText(this, "Low Storage", Toast.LENGTH_LONG).show();
Log.w(TAG, "Low Storage");
}
this.finish();
}
try {
cameraSource.release();
}catch (NullPointerException e){
Log.e("Camera Realease", "Yes");
Toast.makeText(scanActivity.this,"Camerea Release ",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
cameraSource=new CameraSource.Builder(this,barcodeDetector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(24)
.setAutoFocusEnabled(true)
.setRequestedPreviewSize(1920,1024)
.build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try
{
cameraSource.start(cameraView.getHolder());
}catch (Exception i){
Log.e("cameraSource start()", "Yes");
i.printStackTrace();
Toast.makeText(scanActivity.this,"Error while opening the camera",Toast.LENGTH_LONG).show();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (barcodes.size()>0){
System.out.println("Barcode "+barcodes.valueAt(0).displayValue);
//Toast.makeText(scanActivity.this,barcodes.valueAt(0).toString(),Toast.LENGTH_LONG);
Intent intent=new Intent();
//storing into global variable
Constants.qrCode=barcodes.valueAt(0).displayValue;
intent.putExtra(BarcodeObject,barcodes.valueAt(0).displayValue);
// //stop the camera
setResult(RESULT_OK,intent);
finish();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
cameraSource=null;
}
}
So I am facing the following error:
I am getting the scanned QR code in the scan activity but the onActivityResult() method in mainActivity.java is not getting called.

interface listener becomes null in fragment even after initialization

I have fragment listener implemented in activity and im initializing it in onAttach() method. In fragment i have been making asynchronous calls and also starting another activity for result. After onActivityResult is called and process the request code then im calling listener implementation in the activity but listener throws NPE always. im very confused to know how the listener variable becomes null after it get results from another activity.
any idea on how its happening?
class ReviewFragment extends Fragment {
private OnReviewContinueButtonClickListener mListener;
/* many other variables */
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CODE_INSTAMOJO_PAYMENT) {
mListener.onContinueButtonClick(mailId);
showSuccessScreen(mailId);
}
if (requestCode == PaytmWalletManager.REQUEST_CODE_REGISTER_PAYTM_WALLET || requestCode == PaytmWalletManager.REQUEST_CODE_ADD_MONEY) {
initiatePaytmPayment();
}
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnReviewContinueButtonClickListener) {
mListener = (OnReviewContinueButtonClickListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnReviewContinueButtonClickListener");
}
}
/* im calling this function middle of fragment from asynchronous network call onsuccess method without runonuithread() */
private void pay(JSONObject paymentObject) throws JSONException {
Intent payment = new Intent(getActivity().getApplicationContext(), WebviewActivity.class);
Bundle bundle = new Bundle(3);
bundle.putString(WebviewActivity.TITLE, "Make Payment");
startActivityForResult(payment, REQUEST_CODE_INSTAMOJO_PAYMENT);
hideProgressDialog();
}
// on calling this method from asynchronous network result onSuccess()
private void registerForFree(String orderId, String paymentId) {
AppEventTracker.logEvent("register for free clicked", "success", "Flight Booking");
getApp().getAccountManager().registerFreeTicketPatchCall(orderId, paymentId, getFreeTicketRegisterBody(), new Callback<JsonElement>() {
#Override
public void success(JsonElement jsonElement, Response response) {
if (getActivity() == null) return;
hideProgressDialog();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mListener.onContinueButtonClick(mailId); // mlistener is null here even though it has been initialized on onAttach().
}
});
}
#Override
public void failure(RetrofitError error) {
if (getActivity() == null) return;
hideProgressDialog();
if (showErrorDialog) {
showErrorDialog = false;
showPriceChangeDiaglog("Error in payment generation");
}
AppEventTracker.logEvent("register for free clicked", "failure", "Explara buy Ticket");
}
});
}
Activity which implements above fragment is
class booking extends Activity implements ReviewFragment.OnReviewContinueButtonClickListener{
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PaytmWalletManager.REQUEST_CODE_REGISTER_PAYTM_WALLET || requestCode == PaytmWalletManager.REQUEST_CODE_ADD_MONEY) {
ReviewItineraryFragment fragment = (ReviewItineraryFragment) getFragmentManager().findFragmentByTag("ReviewItinerary");
fragment.initiatePaytmPayment();
}
}
}
#Override
public void onContinueButtonClick(String mail) {
showSuccessScreen(mail);
}
private void showSuccessScreen(String mail) {
if (this != null && !this.isFinishing()) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setTitle("Order Confirmation");
FragmentTransaction transaction = this.getFragmentManager().beginTransaction();
String email = mail;
String type = "Order";
transaction.replace(R.id.container, PaymentSuccess.newInstance(email, type));
transaction.addToBackStack(null);
transaction.commit();
}
}
}

Facebook SDK - how to override onActivityResult() correctly?

I have a simple Activity in which I want to get some information about the Facebook user:
public class FacebookActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_layout);
// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.
GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Log.i("facebook_id", user.getId());
Log.i("facebook_name", user.getName());
}
}
});
}
}
});
}
}
But onCompleted() method is not called if the onActivityResult() method is not overridden. So, my question is how to make it correctly in my case?
Thanks.
try that
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}

an attempt was made to request new permissions for a session that has a pending request.Android

I have implemented fb integration and i am getting users details by setting some permissions but it is giving me error java.lang.UnsupportedOperationException: Session: an attempt was made to request new permissions for a session that has a pending request.
when i run first time and second time it it is not giving me this exception, i am using the latest fb SDK for integration. I'll post me code.
public class MainActivity extends Activity {
Button loginbtn;
Session session = Session.getActiveSession();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginbtn = (Button)findViewById(R.id.loginbutton);
loginbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,FacebookLogin.class);
startActivity(intent);
}
});
}
}
public class FacebookLogin extends Activity{
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, Arrays.asList("email,user_birthday,user_location,user_hometown,user_about_me,user_relationships"));
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.facebooklogin);
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#SuppressWarnings("deprecation")
#Override
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// Log.i("session.isOpened", "session.isOpened");
session.requestNewReadPermissions(newPermissionsRequest);
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
//session.requestNewReadPermissions(newPermissionsRequest);
//System.out.println("Response : "+response.toString());
Log.i("Response", response.toString());
if (user != null) {
Log.i("USERName", ""+user.getName());
Log.i("Birthday", ""+user.getBirthday());
Log.i("LastName", ""+user.getLastName());
Log.i("FirstName", ""+user.getFirstName());
Log.i("getId", ""+user.getId());
Log.i("email", " "+user.getLink()+" email : ) "+user.asMap().get("email"));
Log.i("location", ""+user.asMap().get("location"));
Log.i("gender", ""+user.asMap().get("gender"));
/* Intent i =new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);*/
finish();
}
}
});
}
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i(" onResume()", "called");
};
#Override
public void onStart() {
Log.i(" onStart", "called");
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("onActivityResult", "called");
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
final Session session = Session.getActiveSession();
if (session.isOpened()) {
session.requestNewReadPermissions(newPermissionsRequest);
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
//session.requestNewReadPermissions(newPermissionsRequest);
Log.i("USERName2", ""+user.getName());
Log.i("Birthday2", ""+user.getBirthday());
Log.i("LastName2", ""+user.getLastName());
Log.i("FirstName2", ""+user.getFirstName());
Log.i("email2", " "+user.getLink()+" email : ) "+user.asMap().get("email"));
Log.i("location", ""+user.asMap().get("location"));
Log.i("gender", ""+user.asMap().get("gender"));
/* Intent i =new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();*/
//Log.i("USERName", ""+user.getName());
}
}
});
}else {
finish();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.i("onSaveInstanceState", "called");
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
}
Update the Active Session using onActivityResult method.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}

Categories

Resources