Android In App purchase - Could not find a method - android

I'm following this tutorial to implement in-app purchases, however I'm doing it in a fragment. For both the public void buttonClicked and public void buyClick it says they have never been used, making the app crash when the button is press. I'm not sure whats going wrong.
Error is
java.lang.IllegalStateException: Could not find a method buyClick(View) in the activity class
public class Fragment_1 extends Fragment {
IabHelper mHelper;
private Button clickButton;
private Button buyButton;
private static final String TAG =
"com.appal.inappbilling";
static final String ITEM_SKU = "android.test.purchased";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_1,
container, false);
Button buyButton = (Button) view.findViewById(R.id.buyButton);
Button clickButton = (Button) view.findViewById(R.id.clickButton);
clickButton.setEnabled(false);
String base64EncodedPublicKey =
"MYKEY";
mHelper = new IabHelper(getActivity(), base64EncodedPublicKey);
mHelper.startSetup(new
IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result)
{
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " +
result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
return view;
}
public void buttonClicked (View view)
{
clickButton.setEnabled(false);
buyButton.setEnabled(true);
}
public void buyClick(View view) {
mHelper.launchPurchaseFlow(getActivity(), ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
}
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data)
{
if (!mHelper.handleActivityResult(requestCode,
resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
= new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase)
{
if (result.isFailure()) {
// Handle error
return;
}
else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
buyButton.setEnabled(false);
}
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// Handle failure
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase,
IabResult result) {
if (result.isSuccess()) {
clickButton.setEnabled(true);
} else {
// handle error
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#000000"
android:orientation="vertical"
tools:context=".Fragment_1">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Listen to"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#DEC779" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="gfhfghfg"
android:textColor="#FFFFFF"
android:gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#id/textView1"
android:layout_above="#id/textView2">
<Button
android:id="#+id/buyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawableRight="#drawable/playiconw"
android:text="Best"
android:textColor="#FFFFFF"
android:layout_below="#+id/textView1"
android:layout_weight="1"
android:onClick="buyClick" />
<Button
android:id="#+id/clickButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawableRight="#drawable/playiconw"
android:text="Feel"
android:textColor="#FFFFFF"
android:layout_below="#+id/button1"
android:layout_weight="1"
android:onClick="buttonClicked"/>

Problem is that hosting Activity is receiving button clicks not the fragment. You could set listeners to corresponding buttons with .setOnClickListener() or do something like this in your hosting activity:
public void buyClick(View view) {
Fragment_1_instance.buyClick(view);
}

Related

dm77 barcodescanner Zbar camera Preview delay in fragment

Hi I am using this library for my android bar code reader and it is working fine with activities but it give some what delay in initiate(Not smooth like when it use in the Activities)when use with the fragment any solution for this.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_gravity="top"
android:minHeight="?attr/actionBarSize"
android:background="#color/actionbar_opacity"
app:theme="#style/TransparentToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<RelativeLayout
android:id="#+id/btn_enable_qr"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginBottom="55dp"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:clickable="true"
android:layout_gravity="bottom"
android:background="#drawable/circle_layout_for_start_scan">
</RelativeLayout>
</RelativeLayout>
This is My Fragment & when application start I set this fragment to my main activity
public class ScannerFragment extends Fragment implements ZBarScannerView.ResultHandler {
private ZBarScannerView mScannerView;
private FrameLayout contentFrame;
RelativeLayout enableQR;
private static final int ZBAR_CAMERA_PERMISSION = 1;
public static ScannerFragment newInstance() {
return new ScannerFragment();
}
#SuppressLint("ClickableViewAccessibility")
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = null;
try {
rootView = inflater.inflate(R.layout.activity_full_scanner, container, false);
contentFrame = (FrameLayout) rootView.findViewById(R.id.content_frame);
enableQR = (RelativeLayout) rootView.findViewById(R.id.btn_enable_qr);
enableQR.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
launchActivity();
break;
}
case MotionEvent.ACTION_UP: {
releaseCamera();
}
}
return true;
}
});
} catch (Exception e) {
// Log.e(TAG, "onCreateView: " + e.toString());
}
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
public void launchActivity() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.CAMERA}, ZBAR_CAMERA_PERMISSION);
} else {
setUpQrScanner();
}
}
public void setUpQrScanner() {
mScannerView = new ZBarScannerView(getActivity());
mScannerView.setFormats(BarcodeFormat.ALL_FORMATS);
contentFrame.addView(mScannerView);
mScannerView.setResultHandler(ScannerFragment.this);
mScannerView.startCamera(-1);
mScannerView.setAutoFocus(true);
}
public void releaseCamera() {
mScannerView.stopCamera();
contentFrame.removeView(mScannerView);
}
#Override
public void handleResult(Result rawResult) {
try {
scannerSoundAndVibration();
} catch (Exception e) {}
Toast.makeText(getActivity(), "Result" + rawResult.getContents()+" TYPE: "+rawResult.getBarcodeFormat().getId(), Toast.LENGTH_LONG).show();
}
#Override
public void onPause() {
super.onPause();
}
private void scannerSoundAndVibration() {
/**
* scanner sound alert time in millisecond
*/
final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 200);
tg.startTone(ToneGenerator.TONE_CDMA_KEYPAD_VOLUME_KEY_LITE);
/**
* scanner vibration alert time in millisecond
*/
Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(250);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case ZBAR_CAMERA_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setUpQrScanner();
} else {
Toast.makeText(getActivity(), "Please grant camera permission to use the QR Scanner", Toast.LENGTH_SHORT).show();
}
return;
}
}
}

i can't log in and get information if facebook app installed on android

I have following problem with facebook app.
I have a simple application 'myapp' where you find a simple button 'log in to facebook'
It displays a pop-up where you can type your email/password to log in.
After that, button changes his text to 'log out'
This code works fine if the user does not have facebook app installed on his phone. However,it does not work if user has facebook app on his phone.
I did not find the root cause for this problem because the code works fine if there is no facebook app installed on the phone
Below is the source code:
public class Facebook extends FragmentActivity {
private LoginButton loginBtn;
private TextView username;
private UiLifecycleHelper uiHelper;
Button post;
Bitmap bitmap=null;
URL imageURL=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, statusCallback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook);
username = (TextView) findViewById(R.id.username);
loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
post = (Button)findViewById(R.id.button1);
post.setVisibility(View.INVISIBLE);
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
postStatusUpdate(arg0);
}
});
loginBtn.setReadPermissions(Arrays.asList("email"));
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
username.setText("You are currently logged in as " + user.getName());
String userID=user.getId();
} else {
username.setText("You are not logged in.");
}
}
});
}
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
post.setVisibility(post.VISIBLE);
Toast.makeText(getApplicationContext(), session.getAccessToken(), Toast.LENGTH_LONG).show();
Log.d("MainActivity", "Facebook session opened.");
} else if (state.isClosed()) {
post.setVisibility(post.INVISIBLE);
Log.d("MainActivity", "Facebook session closed.");
}
}
};
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
}
Resource file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:facebook="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.facebook.widget.LoginButton
android:id="#+id/fb_login_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
facebook:confirm_logout="false"
facebook:fetch_user_info="true" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:textSize="16sp" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>

Google plus login from one activity and logout from second activity by clicking the logout button in second activity

Google plus login from one activity (this activity stored the login details in shared preference) and logout from another activity (this activity retreives the login details).Logout activity has the logout button.
My issue:I need to login from first activity (AndroidGooglePlusExample) and the login details (username,userimage,emailid) are stored in shared preference. I retreive these values in second activity(HomePage), and display it there, and from this second activity I need to logout on clicking the logout button. Please help me to solve this issue .This is my login activity
public class AndroidGooglePlusExample extends Activity implements OnClickListener, ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
// Google client to communicate with Google
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean signedInUser;
private ConnectionResult mConnectionResult;
private SignInButton signinButton;
private ImageView image;
private TextView username, emailLabel;
private LinearLayout profileFrame, signinFrame;
private SharedPreferences mPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signinButton = (SignInButton) findViewById(R.id.button1);
signinButton.setOnClickListener(this);
// image = (ImageView) findViewById(R.id.image);
// username = (TextView) findViewById(R.id.username);
// emailLabel = (TextView) findViewById(R.id.email);
profileFrame = (LinearLayout) findViewById(R.id.profileFrame);
// signinFrame = (LinearLayout) findViewById(R.id.signinFrame);
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(Plus.API, Plus.PlusOptions.builder().build()).addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
if (!mIntentInProgress) {
// store mConnectionResult
mConnectionResult = result;
if (signedInUser) {
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
switch (requestCode) {
case RC_SIGN_IN:
if (responseCode == RESULT_OK) {
signedInUser = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
break;
}
}
#Override
public void onConnected(Bundle arg0) {
signedInUser = false;
Toast.makeText(this, "Connected", Toast.LENGTH_LONG).show();
getProfileInformation();
}
private void updateProfile(boolean isSignedIn) {
// if (isSignedIn) {
// signinFrame.setVisibility(View.GONE);
// profileFrame.setVisibility(View.VISIBLE);
//
// } else {
// signinFrame.setVisibility(View.VISIBLE);
// profileFrame.setVisibility(View.GONE);
// }
if (isSignedIn) {
Intent intent = new Intent(AndroidGooglePlusExample.this, HomePage.class);
startActivity(intent);
}
}
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
username.setText(personName);
emailLabel.setText(email);
new LoadProfileImage(image).execute(personPhotoUrl);
// update profile frame with new info about Google Account
// profile
updateProfile(true);
//storing details in shared preference
if(mPrefs == null){
mPrefs = this.getSharedPreferences("MyGamePreferences", android.content.Context.MODE_PRIVATE);
}
SharedPreferences.Editor editor = mPrefs.edit();
//editor.putInt("login",401);
editor.putString("Guser_name", personName);
editor.putString("Guserpic_url", personPhotoUrl);
editor.putString("Guser_email", email);
editor.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
updateProfile(false);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
googlePlusLogin();
break;
}
}
public void signIn(View v) {
googlePlusLogin();
}
// public void logout(View v) {
// googlePlusLogout();
// }
private void googlePlusLogin() {
if (!mGoogleApiClient.isConnecting()) {
signedInUser = true;
resolveSignInError();
}
}
// private void googlePlusLogout() {
// if (mGoogleApiClient.isConnected()) {
// Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
// mGoogleApiClient.disconnect();
// mGoogleApiClient.connect();
// updateProfile(false);
// }
// }
// download Google Account profile image, to complete profile
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView downloadedImage;
public LoadProfileImage(ImageView image) {
this.downloadedImage = image;
}
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
Bitmap icon = null;
try {
InputStream in = new java.net.URL(url).openStream();
icon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return icon;
}
protected void onPostExecute(Bitmap result) {
downloadedImage.setImageBitmap(result);
}
}
}
This is my second activity
public class HomePage extends Fragment {
SharedPreferences mPrefs;
Button logout_btn;
// Google client to communicate with Google
private GoogleApiClient mGoogleApiClient;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.activity_home_page, container, false);
// TextView name =(TextView)rootView.findViewById(R.id.username);
// TextView emailid =(TextView)rootView.findViewById(R.id.email);
// ImageView myimage=(ImageView)rootView.findViewById(R.id.image);
logout_btn=(Button)rootView.findViewById(R.id.logout);
logout_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editor editor = mPrefs.edit();
String name = mPrefs.getString("Guser_name", "");
Log.d("", name);
String pic = mPrefs.getString("Guserpic_url", "");
String email = mPrefs.getString("Guser_email", "");
}
public void logout(View v) {
googlePlusLogout();
}
private void googlePlusLogout() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
// updateProfile(false);
}
}
});
return rootView;
}
}
this is my login xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="15dp"
tools:context=".AndroidGooglePlusExample" >
<LinearLayout
android:id="#+id/signinFrame"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:gravity="center"
android:orientation="vertical"
android:visibility="visible" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="#string/loginText"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ffffff" />
<com.google.android.gms.common.SignInButton
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:textSize="18dp" />
logout xml
<LinearLayout
android:id="#+id/profileFrame"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:gravity="center"
android:orientation="vertical"
>
<ImageView
android:id="#+id/image"
android:layout_width="80dp"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="20dp" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="16dp" />
<Button
android:id="#+id/logout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="logout"
android:padding="10dp"
android:text="#string/logout"
android:textSize="18dp" />
</LinearLayout>
As per the initial chat discussion, you have a working code example for implementation of Android Login with Google Plus Account but you need to modify it with as per your requirement. I can give an idea only but unable to give an example for it !!
So here is my suggestions to meet your task completion.
As you mentioned in the post your able to login with Google+ account successfully. After successful login you need to store the credentials of the user (user name & password) in Shared Preferences along with a Boolean value (true/false) as a login status (logged-in /logged-out)
Then when your navigating to the second screen you can place a button in that and set an action to it for logout. after clicking the button you need to check the Boolean value in the shared preferences and if it is login you can logout the Google+ and update your preferences with new values ( username - null, password -null , Boolean status -false)
This links may help you to Role on
Start integrating Google+ into your Android
Google Plus Account in Android Example

Custom Facebook Login Button - Android

I''m following this Tutorial but so far I can't make it work, though this is from a year ago or so...
I'm using androidStudo 1.2.2 and FacebookSDK 4.
I want a simple login into facebook using a custom button, like the one shown in this image:
Now, in the example from the tutorial I'm having problems with the Session variable, it says it cannot resolve it, neither getActivity()
Has naybody tried this on FacebookSDK4.0?
Is that a correct approach or maybe there is something more updated?
Step 1:
First add FrameLayout and make facebook button visibility="gone" and add your custom button.
Don't forgot to put xmlns:facebook="http://schemas.android.com/apk/res-auto" in your main layout.
<FrameLayout
android:id="#+id/FrameLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<Button
android:id="#+id/fb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#416BC1"
android:onClick="onClick"
android:text="FaceBook"
android:textColor="#ffffff"
android:textStyle="bold" />
</FrameLayout>
Step 2:
Initialize FacebookSdk in onCreate before inflecting layout.
FacebookSdk.sdkInitialize(this.getApplicationContext());
Step 3: add this into your java file.
callbackManager = CallbackManager.Factory.create();
fb = (Button) findViewById(R.id.fb);
loginButton = (LoginButton) findViewById(R.id.login_button);
List < String > permissionNeeds = Arrays.asList("user_photos", "email",
"user_birthday", "public_profile", "AccessToken");
loginButton.registerCallback(callbackManager,
new FacebookCallback < LoginResult > () {#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("onSuccess");
String accessToken = loginResult.getAccessToken()
.getToken();
Log.i("accessToken", accessToken);
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
Log.i("LoginActivity",
response.toString());
try {
id = object.getString("id");
try {
URL profile_pic = new URL(
"http://graph.facebook.com/" + id + "/picture?type=large");
Log.i("profile_pic",
profile_pic + "");
} catch (MalformedURLException e) {
e.printStackTrace();
}
name = object.getString("name");
email = object.getString("email");
gender = object.getString("gender");
birthday = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields",
"id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception) {
System.out.println("onError");
Log.v("LoginActivity", exception.getCause().toString());
}
});
Step 4:
Don't forget to add following code.
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent data) {
super.onActivityResult(requestCode, responseCode, data);
callbackManager.onActivityResult(requestCode, responseCode, data);
}
Step 5:
Set your custom button click to FacebookLogin button click.
public void onClick(View v) {
if (v == fb) {
loginButton.performClick();
}
}
Step 6:
For programmatically logout use this.
LoginManager.getInstance().logOut();
Step 7: you can find user logged in or not by profile.
profile = Profile.getCurrentProfile().getCurrentProfile();
if (profile != null) {
// user has logged in
} else {
// user has not logged in
}
IMO part of the selected answer is kind of work-around not the proper solution.
So what needs to be changed to make it proper is the following:
Get rid of "com.facebook.login.widget.LoginButton" from your XML
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
Get rid of all references to the "LoginButton" in your Java code
Use Facebook's "LoginManager" class which is there for that purpose as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
// Some code
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(
callbackManager,
new FacebookCallback < LoginResult > () {
#Override
public void onSuccess(LoginResult loginResult) {
// Handle success
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
}
);
}
public void onClick(View v) {
if (v == fb) {
LoginManager.getInstance().logInWithReadPermissions(
this,
Arrays.asList("user_photos", "email", "user_birthday", "public_profile")
);
}
}
// this part was missing thanks to wesely
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
This is very simple.
Add a button in the layout file like
<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Login with facebook"
android:textColor="#ffff"
android:layout_gravity="center"
android:textStyle="bold"
android:onClick="fbLogin"
android:background="#color/colorPrimary"/>
And in the onClick place the LoginManager's registercallback() method
Becuse the this method automatically executes.
like:
public void fbLogin(View view)
{
// Before Edit:
// LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("user_photos", "email", "public_profile", "user_posts" , "AccessToken"));
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("user_photos", "email", "public_profile", "user_posts"));
LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess(LoginResult loginResult)
{
// App code
}
#Override
public void onCancel()
{
// App code
}
#Override
public void onError(FacebookException exception)
{
// App code
}
});
}
Have Fun
(don't have enough reputation to add a comment ...)
I tried the #Shehabix's answer, can't receive callback until I add this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
then it works fine.
The Simple answer is add facebookButton.performClick() inside cutomBtn.setOnClickListener
<!-- connect with Facebook -->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.facebook.login.widget.LoginButton
android:id="#+id/fb_connect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:textSize="#dimen/login_fb_font_size"
android:visibility="invisible" />
<LinearLayout
android:id="#+id/mfb_connect"
style="#style/facebook_button">
<ImageView
style="#style/login_connect_icon"
android:src="#drawable/ic_facebook" />
<TextView
style="#style/login_connect_text"
android:text="#string/login_connect_facebook" />
</LinearLayout>
</RelativeLayout>
...
private LoginButton fb_connect;
private LinearLayout mfb_connect;
...
// the button from facebook sdk
fb_connect = (LoginButton) findViewById(R.id.fb_connect);
// handle the click from my custom button to perfrom action click on facebook sdk button
mfb_connect = (LinearLayout) findViewById(R.id.mfb_connect);
mfb_connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fb_connect.performClick();
}
});
That will achieve this:
i just call the facebook default button from my custom button and left every single line of code as documented. and bang it works successfully.
public class SignInFragment extends Fragment implements
FragmentChangeListener{
private Button facebook
private FirebaseAuth firebaseAuth;
private CallbackManager mCallBackManager;
private LoginButton loginButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_sign_in, container, false);
facebook = view.findViewById(R.id.facebookButton);
loginButton = view.findViewById(R.id.facebookBtn);
firebaseAuth = FirebaseAuth.getInstance();
facebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.callOnClick();
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallBackManager = CallbackManager.Factory.create();
loginButton.setFragment(SignInFragment.this);
loginButton.setPermissions("email","public_profile");
loginButton.registerCallback(mCallBackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Toast.makeText(getContext(),"Is Cancelled",Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallBackManager.onActivityResult(requestCode, resultCode, data);
}
private void handleFacebookAccessToken(AccessToken token) {
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = firebaseAuth.getCurrentUser();
startActivity(new Intent(getContext(),MainActivity.class));
} else {
// If sign in fails, display a message to the user.
Toast.makeText(getContext(), task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
}
Complementing the answers by Harvi and Shehabix, I would suggest to add this method as this registers the authentication in Firebase Auth.
This method should be called inside "On Success" of LoginManager.
private void handleFacebookAccessToken(AccessToken token) {
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//Toast.makeText(MainActivity.this, "Autenticando",Toast.LENGTH_SHORT).show();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
//updateUI(null);
}
}
});
}
try this
// Facebook Button
LoginButton loginButton = findViewById(R.id.loginbtn);
loginButton.setVisibility(View.GONE)
// Your Custom Button
binding.fbBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginButton.callOnClick();
}
});

Want to remove ads through InAppPurchase

I have implemented admob interstitial in my android app. But I want to disable ads if users are ready to pay. i.e InAppPurchase. I have written below code for IAP and have also published apk in beta testing with product. But still it is showing that "No product found", when I am pressing "remove ads" button.
Anybody can help me to write a true code or check out that below code is right or wrong for IAP?
public static final String PRO_SKU = "removeads";
private final String BASE_64_PUBLIC_KEY = "KEY";
private Inventory mInventory;
IabHelper mHelper;
public static boolean isPro;
private InterstitialAd interstitial;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);}
interstitial = new InterstitialAd(getActivity(),
"AD UNIT");
AdRequest adRequest = new AdRequest();
interstitial.loadAd(adRequest);
mHelper = new IabHelper(getActivity().getApplicationContext(),
BASE_64_PUBLIC_KEY);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener()
{
#Override
public void onIabSetupFinished(IabResult result)
{
if (result.isSuccess())
{
loadInventory();
Log.d("IAP", "IAP Setup Succesful yeah!");
} else
{
Log.d("IAP", "IAP Setup Failed");
}
}
});
;
//AD CODE
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_quality, container,
false);
ImageView purchaseAds = (ImageView) rootView.findViewById(R.id.promo);
purchaseAds.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
purchasePro(PRO_SKU);
}
});
private void loadInventory() {
mHelper.queryInventoryAsync(true,
new IabHelper.QueryInventoryFinishedListener() {
#Override
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isSuccess()) {
mInventory = inventory;
Log.d("IAP inventory loader", "inventory loaded");
if (inventory.hasPurchase(PRO_SKU)) {
isPro = true;
Log.d("IAP inventory checker", "purchased");
} else {
Log.d("IAP inventory checker", "not purchased");
isPro = false;
}
} else {
Log.d("IAP inventory loader","inventory not loaded");
}
}
});
}
private void purchasePro(String sku) {
mHelper.launchPurchaseFlow(getActivity(), sku, 1000,
new IabHelper.OnIabPurchaseFinishedListener() {
#Override
public void onIabPurchaseFinished(IabResult result,
Purchase info) {
if (result.isSuccess()) {
isPro = true;
Log.d("IAP purchase person", "purchased!");
} else {
Toast.makeText(
getActivity().getApplicationContext(),
"Error in your purchase",
Toast.LENGTH_SHORT).show();
Log.d("IAP purchase person", "not purchased!");
}
}
}, null);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!mHelper.handleActivityResult(1000, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
}

Categories

Resources