Facebook - Post to wall - java

I have this code.. The only working here is the Login... I want to achieve the Publish to wall or feed dialog.. I have here the code for the wall post but It still not working.. Any help will be appreciated... I followed this link for my Login
[a link] http://www.kpbird.com/2013/03/android-login-using-facebook-sdk-30.html
I am trying to embed the post status in this Login..
public class FacebookActivity extends FragmentActivity {
private Button publishButton;
private String TAG = "FacebookActivity";
private TextView lblEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_activity);
lblEmail = (TextView) findViewById(R.id.lblEmail);
LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
authButton.setOnErrorListener(new OnErrorListener(){
#Override
public void onError(FacebookException error) {
Log.i(TAG, "Error " + error.getMessage());
}
// TODO Auto-generated method stub
});
// set permission list, Don't forget to add email
authButton.setReadPermissions(Arrays.asList("basic_info","email"));
// session state call back event
authButton.setSessionStatusCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Log.i(TAG,"Access Token"+ session.getAccessToken());
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,Response response) {
if (user != null) {
Log.i(TAG,"User ID "+ user.getId());
Log.i(TAG,"Email "+ user.asMap().get("email"));
lblEmail.setText(user.asMap().get("email").toString());
}
}
});
publishButton.setVisibility(View.VISIBLE);
}
else if (state.isClosed()) {
publishButton.setVisibility(View.INVISIBLE);
}
}
});
publishButton = (Button) findViewById(R.id.publishButton);
publishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishFeedDialog();
}
});
}
private void publishFeedDialog() {
Bundle params = new Bundle();
params.putString("name", "Facebook SDK for Android");
params.putString("caption", "Build great social apps and get more installs.");
params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
params.putString("link", "https://developers.facebook.com/android");
params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(getActivity(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getActivity(),
"Posted story, id: "+postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(getActivity().getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(getActivity().getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(getActivity().getApplicationContext(),
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
})
.build();
feedDialog.show();
}
protected ContextWrapper getActivity() {
// TODO Auto-generated method stub
return null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}

Related

application started crashing when trying to login using facebook after ide error

My application was working perfectly then, after adding the following code LoginManager.getInstance().logOut(); to disconnect from the current facebook account (a developper acount), the ide showed that an error occurred while running the app, but the application launched anyway, but when trying to login, it crashed and now it's not logging in, it keeps crashing! even though I changed nothing except adding that line of code to the next activity to make the app disconnect in case the user want to logout!
here's my java code:
public class ConnexionActivity extends AppCompatActivity {
Button b_bb, b_back, ee, b_inscrp_formulaire, fb;
EditText tb_pseudo, tb_mdp;
int id;
String name, gender, email, birthday;
private LoginButton loginButton;
private CallbackManager callbackManager;
Profile profile;
//new try:
private AccessTokenTracker accessTokenTracker;
private Button customFacebookLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
/*List<String> permissionNeeds = Arrays.asList("user_photos", "email",
"user_birthday", "public_profile", "AccessToken");*/
setContentView(R.layout.activity_connexion);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
b_inscrp_formulaire = (Button) findViewById(R.id.b_inscrip_formulaire);
fb = (Button) findViewById(R.id.fb);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setText("");
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_friends", "user_birthday"));
//"user_photos", "email","user_birthday", "public_profile"
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
//getting the hash key
try {
PackageInfo info = getPackageManager().getPackageInfo(
"your.package",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
//2nd way to generate hash key (or get it)
try {
PackageInfo info = getPackageManager().getPackageInfo("your.package.name", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
b_bb = (Button) findViewById(R.id.b_bb);
b_back = (Button) findViewById(R.id.b_back);
tb_pseudo = (EditText) findViewById(R.id.textbox_pseudo);
tb_mdp = (EditText) findViewById(R.id.textbox_mdp);
/////////////
ee = (Button) findViewById(R.id.button);
////////////
b_bb.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
b_bb.setBackgroundResource(R.drawable.button_bb_selec);
break;
}
case MotionEvent.ACTION_UP: {
b_bb.setBackgroundResource(R.drawable.button_bb);
break;
}
}
return false;
}
});
b_bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isAuthorized()) {
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", tb_pseudo.getText().toString());
startActivity(menu_p);
} else {
openDialog();
}
}
});
b_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnexionActivity.this.finish();
}
});
ee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", "Easter");
startActivity(menu_p);
}
});
b_inscrp_formulaire.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu_p = new Intent(ConnexionActivity.this, InscriptionActivity.class);
startActivity(menu_p);
}
});
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
fb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(ConnexionActivity.this, Arrays.asList("user_photos", "email",
"user_birthday", "public_profile"));
profile = Profile.getCurrentProfile().getCurrentProfile();
if (profile != null) {
// user has logged in
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", profile.getFirstName());
startActivity(menu_p);
Toast.makeText(getApplicationContext(), "Connecté : " + profile.getFirstName() + " " + profile.getLastName(), Toast.LENGTH_SHORT).show();
} else {
// user has not logged in
Toast.makeText(getApplicationContext(), "Non-Connecté : Erreur de connexion!!", Toast.LENGTH_SHORT).show();
}
}
});
//To log out of FB:
/*LoginManager.getInstance().logOut();*/
//TODO: check if the user is logged in or not
/* profile = Profile.getCurrentProfile().getCurrentProfile();
if (profile != null) {
// user has logged in
} else {
// user has not logged in
}*/
}
private Boolean isAuthorized() {
if (tb_pseudo.getText().toString().equals("Admin")
&& tb_mdp.getText().toString().equals("0000")
) {
return true;
} else
return false;
}
public void openDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Mauvaise combinaison \"Pseudo\", \"Mot de passe\"");
alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
public void graphRequest(AccessToken token) {
GraphRequest request = GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Toast.makeText(getApplicationContext(), object.toString(), Toast.LENGTH_LONG).show();
}
});
Bundle b = new Bundle();
b.putString("fields", "id,email,first_name,last_name,picture.type(large)");
request.setParameters(b);
request.executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
I guess the problem was just in the IDE, something about indexation!! I closed and reopened the IDE and everything is working just fine.

Facebook API doesn't return email

I know that this question has been asked, but there is only one answer pretty much or is not even answered.
I dont know if it's my lack of understanding or lack of Facebook documentation, but so far i have this code to retrieve user email.
callbackManager = CallbackManager.Factory.create();
mFbLoginManager.registerCallback(
callbackManager,
new FacebookCallback < LoginResult > () {
#Override
public void onSuccess(final LoginResult loginResult) {
// Handle success
Log.i(TAG, "callBack Login Result: LoginManager success - " + loginResult.toString());
GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject userObject, GraphResponse response) {
if (response.getError() == null) {
try {
AccessToken token = AccessToken.getCurrentAccessToken();
Log.e(TAG, token.getToken());
Log.e(TAG, userObject.toString());
email = userObject.getString("email");
} catch (JSONException ex) {
Log.e(TAG, "Not such permissions for email!");
ex.printStackTrace();
}
Log.d(TAG, "Email fetched: " + email);
}else{
Log.e(TAG, "Something went wrong with fetching email with GraphRequest");
}
}
}).executeAsync();
}
The JSON string returns only the name and the id, therefore my email variable is empty.
The part i am troubled with is that when i test it on Graph Explorer or with that link, i get the email.
I have se permissions also on the developers site dashboard and also in my code(that's inside onClick() when user press the facebook login button):
mFbLoginManager.logInWithReadPermissions(LoginActivity.this, Arrays.asList("user_photos", "email", "public_profile")
So i am not sure what is the problem in my code. The login button is custom and not the facebook LoginButton, i dont know if that matters.
Every help is welcome
Add below depandancy in Gradle
implementation 'com.facebook.android:facebook-android-sdk:4.11.0'
enter code here
FacebookSdk.sdkInitialize(this);
callbackManager =CallbackManager.Factory.create();
// -----start putting in oncreate-----------------------
LoginManager.getInstance().logInWithReadPermissions(UserActivity.this, Arrays.asList("public_profile", "user_friends","email"));
facebookTime();
//----onclicklisterner ---------------/
callbackManager.onActivityResult(requestCode,resultCode,data);
//---onactivityresult-------------/
public void facebookTime() {
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("Success");
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Util.showCenteredToast(getActivity(), "object" + object);
// Util.showCenteredToast(getActivity(), "GraphResponse" + response);
try {
strEmail = object.getString("email");
strUserName = object.getString("name");
String id = object.getString("id");
// write your code here
//asyncTask.iSocialMediaResponse = LoginFragment.this;
asyncTask.execute();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,name");
//parameters.putString("fields", "user_friends");
request.setParameters(parameters);
//Log.e(" About to Graph Call", " ");
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Util.showCenteredToast(UserActivity.this, "oncancel");
}
#Override
public void onError(FacebookException exception) {
// App code
Util.showCenteredToast(UserActivity.this, "exception" + exception);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}

google plus login with android redirects back to login screen after button click on attempting to login

I am trying to make a login into my android app. I have generated the google-services.json with the same package name of the class and copied into the app folder of my application. On attempting to login it shows a dim screeen and thereafter shows a white screen of the the page I am trying to login with.
This is the code snippet from my activity class
// Button click listeners
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
btnRevokeAccess.setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
Log.e(TAG, "onCreate End!");
}
protected void onStart() {
Log.e(TAG, "onStart!");
super.onStart();
mGoogleApiClient.connect();
Log.e(TAG, "onStart end!");
}
protected void onStop() {
Log.e(TAG, "onStop!");
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
PendingIntent signInIntent = mConnectionResult.getResolution();
if (signInIntent != null) {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
} else {
showDialog(DIALOG_PLAY_SERVICES_ERROR);
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case DIALOG_PLAY_SERVICES_ERROR:
if (GooglePlayServicesUtil.isUserRecoverableError(mConnectionResult.getErrorCode())) {
return GooglePlayServicesUtil.getErrorDialog(
mConnectionResult.getErrorCode(),
this,
RC_SIGN_IN,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
Log.e(TAG, "Google Play services resolution cancelled");
}
});
} else {
return new AlertDialog.Builder(this)
.setMessage(R.string.play_services_error)
.setPositiveButton(R.string.close,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.e(TAG, "Google Play services error could not be "
+ "resolved: " + mConnectionResult.getErrorCode());
}
}).create();
}
default:
return super.onCreateDialog(id);
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "onConnectionFailed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
Log.i(TAG, "See error types in http://developer.android.com/reference/com/google/android/gms/common/ConnectionResult.html");
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (result.getErrorCode() == ConnectionResult.SIGN_IN_REQUIRED) {
Log.i(TAG, "Error type: SIGN_IN_REQUIRED");
}
if (result.getErrorCode() == ConnectionResult.NETWORK_ERROR ) {
Log.i(TAG, "Error type: NETWORK_ERROR ");
}
if (result.getErrorCode() == ConnectionResult.API_UNAVAILABLE) {
// An API requested for GoogleApiClient is not available. The device's current
// configuration might not be supported with the requested API or a required component
// may not be installed, such as the Android Wear application. You may need to use a
// second GoogleApiClient to manage the application's optional APIs.
} else if (!mIntentInProgress) {
Log.i(TAG, "not IntentInProgress!");
// Store the ConnectionResult for later usage
mConnectionResult = result;
if (mSignInClicked) {
Log.i(TAG, "signInAlreadyClicked! Resolving sign error...");
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
Log.i(TAG, "onConnectionFailed end!");
//TODO: Sign OUT?
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
// Get user's information
getProfileInformation();
// Update the UI after signin
updateUI(true);
}
/**
* Updating the UI, showing/hiding buttons and profile layout
* */
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
btnRevokeAccess.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
btnRevokeAccess.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);
}
}
/**
* Fetching user's information name, email, profile pic
* */
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 personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.i(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);
txtName.setText(personName);
txtEmail.setText(email);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;
new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* Button on click listener
* */
#Override
public void onClick(View v) {
if (!mGoogleApiClient.isConnecting()) {
switch (v.getId()) {
case R.id.btn_sign_in:
// Signin button clicked
signInWithGplus();
break;
case R.id.btn_sign_out:
// Signout button clicked
signOutFromGplus();
break;
case R.id.btn_revoke_access:
// Revoke access button clicked
revokeGplusAccess();
break;
}
}
}
/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
// We only process button clicks when GoogleApiClient is not transitioning
// between connected and not connected.
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Sign-out from google
* */
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}
/**
* Revoking access from google
* */
private void revokeGplusAccess() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status arg0) {
Log.e(TAG, "User access revoked!");
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
});
}
}
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
this is the login button from my page xml file calling the login function to authenticate with google plus
<com.google.android.gms.common.SignInButton
android:id="#+id/btn_sign_in"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"/>
Please why is my app not authenticating with google plus sign. Please assist

In app billing(purchase) linking app with items

I'm trying to implment in app puchase/billing in my app so when the user buys the item i remove the ads. I have and example code that is working with SKU = "android.test.purchased". Now my question is how can I link the app to my items - I have uploaded new apk with billing enabled, created and published the item one hour ago, but when I try to buy the item I get this:
here is my code:
public class RemoveAds extends AthanBaseActivity implements OnClickListener {
private static final String TAG = "inappbilling";
IabHelper mHelper;
//ID from playstore 16xxxx15_removeads.
//android.test.purchased
static final String ITEM_SKU = "com.myapppackage.16xxxx15_removeads.";
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.remove_ads);
findViewById( R.id.remove_ads_).setOnClickListener(this);
setupInAppPurchase();
}
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);
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null)
mHelper.dispose();
mHelper = null;
}
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase, IabResult result) {
if (result.isSuccess()) {
Toast.makeText(RemoveAds.this, "SUCCESS", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(RemoveAds.this, "ERROR purchase",
Toast.LENGTH_LONG).show();
// handle error
}
}
};
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);
}
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
private void setupInAppPurchase() {
String base64EncodedPublicKey = "MIIBIjANBgkqhkcccxxxxxdomr somelongstringdfsdfsdfsfsdofksdofkdsMXz0R4EJuw7YZkQ8jMPemymSbQGtLllH+fu85hfQIDAQAB";
mHelper = new IabHelper(this, 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");
}
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.remove_ads_:
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
break;
}
}
}
You cannot make purchases if the primary account on your real android device is same as your developer account.

post on facebook wall always show login page .. problem android

I'm using graph api from youtube , and i am facing some trouble .
I can send a msg to the wall , it works fine . The problem is that every time , it shows the login page and the user have to click at the ok button to send it. I'd like to send it without showing that page , it should only shows at the first time . I store the token using
shared preferences , but if i dont call the method facebook.autorize , which shows the login page , before trying to send the video , it does not work .
Am i doing it wrong ? thanks for any help .
My code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_lay);
init();
acessToken = loadAccessToken();
Log.i("teste","Acesstoken depois do load : " + acessToken);
if(acessToken == null || acessToken.equals("")){
login();
}else{
Log.i("teste","Session valid com token salva ? " + mFacebook.isSessionValid());
sendVideo();
}
}
private void init(){
mFacebook = new Facebook(APP_ID);
videoUrl = getIntent().getExtras().getString("videoUrl");
preferences = this.getSharedPreferences(APPLICATION_PREFERENCES,
Context.MODE_PRIVATE);
}
private void login(){
mFacebook.authorize(this, new String[] {"publish_stream","offline_access"},new AuthorizeListener());
}
public void postOnWall(String msg) {
Log.i("teste", "Testing graph API wall post");
try {
Bundle parameters = new Bundle();
parameters.putString("message", AUTO_MSG);
parameters.putString("link", msg);
mFacebook.request("me/feed", parameters,
"POST");
} catch(Exception e) {
e.printStackTrace();
}
}
private void storeToken(String token){
Log.i("teste","storeToken: " + token);
Editor editor = preferences.edit();
editor.putString(ACESS_TOKEN, token);
editor.commit();
}
private String loadAccessToken() {
String token = preferences.getString(ACESS_TOKEN, null);
if (token != null && !token.equals("") ) {
return token;
} else {
return null;
}
}
private void sendVideo(){
dialog = ProgressDialog.show(FacebookView.this, "Sending","Enviando video ...");
new Thread(){
public void run() {
postOnWall(videoUrl);
dialog.dismiss();
finish();
};
}.start();
}
class AuthorizeListener implements DialogListener{
#Override
public void onCancel() {
Log.i("teste","Logou candelado!");
finish();
}
#Override
public void onComplete(Bundle values) {
Log.i("teste","Logou com sucesso!");
Log.i("teste", "AcessToken : " + mFacebook.getAccessToken());
Log.i("teste", "AcessToken expires : " + mFacebook.getAccessExpires());
Log.i("teste", "Session valid : " + mFacebook.isSessionValid());
storeToken(mFacebook.getAccessToken());
sendVideo();
}
#Override
public void onError(DialogError e) {
Log.i("teste","Erro ao logar: " + e.getMessage());
finish();
}
#Override
public void onFacebookError(FacebookError e) {
Log.i("teste","FacebookError ao logar: " + e.getMessage());
Log.i("teste","FacebookError ao logar Causa: " + e.getCause());
e.printStackTrace();
finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
package com.greatup;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class MyGreatActivity extends Activity {
/** Called when the activity is first created. */
Facebook facebook = new Facebook("208086425868080");
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// facebook.authorize(this, new String[] { "email", "read_stream" },new DialogListener() {
//
// public void onComplete(Bundle values) {}
//
//
// public void onFacebookError(FacebookError error) {}
//
//
// public void onError(DialogError e) {}
//
// public void onCancel() {}
// });
facebook.dialog(this,"feed",
new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
}
);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
Already find the answer . Just have to set the token on the facebook object .
acessToken = loadAccessToken();
Log.i("teste","Acesstoken depois do load : " + acessToken);
if(acessToken == null || acessToken.equals("")){
login();
}else{
mFacebook.setAccessToken(acessToken);
Log.i("teste","Session valid com token salva ? " + mFacebook.isSessionValid());
sendVideo();
}

Categories