Related
I've created my Cognito User Pool as follows:
settings
for allows users to log in via their email or username (and have them both unique for each user).
This is my Account Cognito implementation:
public class AccountDAO_Cognito implements AccountDAO {
#Override
public boolean authenticate(Account account, Context context) {
CognitoSettings cognitoSettings = new CognitoSettings(context);
cognitoSettings.userLogin(account.getEmail(), account.getPassword());
return true;
}
#Override
public boolean create(Account account, Context context) {
CognitoSettings cognitoSettings = new CognitoSettings(context);
setCognitoSettingsAttributes(cognitoSettings, account);
cognitoSettings.signUpInBackground(account.getEmail(), account.getPassword());
return true;
}
#Override
public boolean updatePassword(Account account, Context context, String newPassword) {
CognitoSettings cognitoSettings = new CognitoSettings(context);
cognitoSettings
.getCognitoUserPool()
.getUser(account.getEmail())
.changePasswordInBackground(account.getPassword(), newPassword, genericHandler);
return true;
}
private void setCognitoSettingsAttributes(CognitoSettings cognitoSettings, Account account) {
cognitoSettings.addAttribute("email", account.getEmail());
cognitoSettings.addAttribute("name", account.getName());
cognitoSettings.addAttribute("family_name", account.getLastname());
}
}
This is my CognitoSettings class
public class CognitoSettings {
private CognitoUserPool cognitoUserPool;
private CognitoUserAttributes cognitoUserAttributes;
private Context context;
private String userPassword;
public CognitoSettings(Context context) {
this.context = context;
String poolID = "SECRET";
String clientID = "SECRET";
String clientSecret = "SECRET";
Regions awsRegion = Regions.US_EAST_1;
cognitoUserPool = new CognitoUserPool(context, poolID, clientID, clientSecret, awsRegion);
cognitoUserAttributes = new CognitoUserAttributes();
}
public void signUpInBackground(String userId, String password) {
cognitoUserPool.signUpInBackground(userId, password, this.cognitoUserAttributes, null, signUpCallback);
}
SignUpHandler signUpCallback = new SignUpHandler() {
#Override
public void onSuccess(CognitoUser cognitoUser, boolean userConfirmed, CognitoUserCodeDeliveryDetails cognitoUserCodeDeliveryDetails) {
// Sign-up was successful
Log.d(TAG, "Sign-up success");
Toast.makeText(context, "Sign-up success, codice inviato a " + cognitoUserCodeDeliveryDetails.getDestination(), Toast.LENGTH_LONG).show();
// Check if this user (cognitoUser) needs to be confirmed
if (!userConfirmed) {
} else {
Toast.makeText(context, "Errore: l'utente era già stato confermato", Toast.LENGTH_LONG).show();
// The user has already been confirmed
}
}
#Override
public void onFailure(Exception exception) {
Toast.makeText(context, "Sign-up failed " + exception.getMessage(), Toast.LENGTH_LONG).show();
Log.d(TAG, "Sign-up failed: " + exception);
}
};
public void confirmUser(String userId, String code) {
CognitoUser cognitoUser = cognitoUserPool.getUser(userId);
cognitoUser.confirmSignUpInBackground(code, false, confirmationCallback);
}
// Callback handler for confirmSignUp API
GenericHandler confirmationCallback = new GenericHandler() {
#Override
public void onSuccess() {
// User was successfully confirmed
Toast.makeText(context, "User Confirmed", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Exception exception) {
// User confirmation failed. Check exception for the cause.
}
};
public void addAttribute(String key, String value) {
cognitoUserAttributes.addAttribute(key, value);
}
public void userLogin(String userId, String password) {
CognitoUser cognitoUser = cognitoUserPool.getUser(userId);
userPassword = password;
cognitoUser.getSessionInBackground(authenticationHandler);
}
// Callback handler for the sign-in process
AuthenticationHandler authenticationHandler = new AuthenticationHandler() {
#Override
public void authenticationChallenge(ChallengeContinuation continuation) {
}
#Override
public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
if (!userSession.isValid())
Toast.makeText(context, "Rifai il login", Toast.LENGTH_SHORT).show();
else
//Toast.makeText(context, "Sign in success", Toast.LENGTH_LONG).show();
}
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
// The API needs user sign-in credentials to continue
AuthenticationDetails authenticationDetails = new AuthenticationDetails(userId, userPassword, null);
// Pass the user sign-in credentials to the continuation
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
// Allow the sign-in to continue
authenticationContinuation.continueTask();
}
#Override
public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) {
// Multi-factor authentication is required; get the verification code from user
//multiFactorAuthenticationContinuation.setMfaCode(mfaVerificationCode);
// Allow the sign-in process to continue
//multiFactorAuthenticationContinuation.continueTask();
}
#Override
public void onFailure(Exception exception) {
// Sign-in failed, check exception for the cause
Toast.makeText(context, "Sign in Failure " + exception.getMessage(), Toast.LENGTH_LONG).show();
}
};
public void tokenIsValid() {
CognitoUser cognitoUser = cognitoUserPool.getCurrentUser();
cognitoUser.getSessionInBackground(authenticationHandler);
}
public CognitoUserPool getCognitoUserPool() {
return cognitoUserPool;
}
}
Unfortunately when I run my android app, it displays an error:
Sign-up failed Username cannot be of email format since user pool is configured for email alias (Service: AmazonCognitoIdentityProvider, Status code: 400, Error Code: InvalidParameterException)
Edit
Note that my client form is structured as follows:
Name, Family Name, Nickname, Email
(for example: John, Petrucci, john_petrucci72, john#example.com)
UPDATE
public class AccountDAO_Cognito implements AccountDAO {
#Override
public boolean authenticate(Account account, Context context) {
CognitoSettings cognitoSettings = new CognitoSettings(context);
cognitoSettings.userLogin(account.getEmail(), account.getPassword());
return true;
}
#Override
public boolean create(Account account, Context context) {
CognitoSettings cognitoSettings = new CognitoSettings(context);
setCognitoSettingsAttributes(cognitoSettings, account);
//cognitoSettings.signUpInBackground(account.getEmail(), account.getPassword());
cognitoSettings.signUpInBackground(account.getNickname(), account.getPassword());
return true;
}
#Override
public boolean isNicknameAvailable(String nickname) {
// Verificare che il nickname sia disponibile (?)
return true;
}
#Override
public boolean updatePassword(Account account, Context context, String newPassword) {
final GenericHandler genericHandler = new GenericHandler() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(Exception exception) {
}
};
CognitoSettings cognitoSettings = new CognitoSettings(context);
cognitoSettings
.getCognitoUserPool()
.getUser(account.getEmail())
.changePasswordInBackground(account.getPassword(), newPassword, genericHandler);
return true;
}
private void setCognitoSettingsAttributes(CognitoSettings cognitoSettings, Account account) {
cognitoSettings.addAttribute("email", account.getEmail());
cognitoSettings.addAttribute("name", account.getName());
cognitoSettings.addAttribute("family_name", account.getLastname());
//cognitoSettings.addAttribute("nickname", account.getNickname());
}
}
and
public class CognitoSettings {
private CognitoUserPool cognitoUserPool;
private CognitoUserAttributes cognitoUserAttributes;
private Context context;
private String userPassword;
public CognitoSettings(Context context) {
this.context = context;
/*String poolID = "SECRET";
String clientID = "SECRET";
String clientSecret = "SECRET";*/
String poolID = "USER_POOL";
String clientID = "CLIENT_ID";
String clientSecret = "CLIENT_SECRET";
Regions awsRegion = Regions.US_EAST_1;
cognitoUserPool = new CognitoUserPool(context, poolID, clientID, clientSecret, awsRegion);
cognitoUserAttributes = new CognitoUserAttributes();
}
public void signUpInBackground(String username, String password) {
cognitoUserPool.signUpInBackground(username, password, this.cognitoUserAttributes, null, signUpCallback);
}
SignUpHandler signUpCallback = new SignUpHandler() {
#Override
public void onSuccess(CognitoUser cognitoUser, boolean userConfirmed, CognitoUserCodeDeliveryDetails cognitoUserCodeDeliveryDetails) {
// Sign-up was successful
Log.d(TAG, "Sign-up success");
Toast.makeText(context, "Sign-up success, codice inviato a " + cognitoUserCodeDeliveryDetails.getDestination(), Toast.LENGTH_LONG).show();
// Check if this user (cognitoUser) needs to be confirmed
if (!userConfirmed) {
} else {
Toast.makeText(context, "Errore: l'utente era già stato confermato", Toast.LENGTH_LONG).show();
// The user has already been confirmed
}
}
#Override
public void onFailure(Exception exception) {
Toast.makeText(context, "Sign-up failed " + exception.getMessage(), Toast.LENGTH_LONG).show();
Log.d(TAG, "Sign-up failed: " + exception);
}
};
public void confirmUser(String userId, String code) {
CognitoUser cognitoUser = cognitoUserPool.getUser(userId);
cognitoUser.confirmSignUpInBackground(code, false, confirmationCallback);
}
// Callback handler for confirmSignUp API
GenericHandler confirmationCallback = new GenericHandler() {
#Override
public void onSuccess() {
// User was successfully confirmed
Toast.makeText(context, "User Confirmed", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Exception exception) {
// User confirmation failed. Check exception for the cause.
}
};
public void addAttribute(String key, String value) {
cognitoUserAttributes.addAttribute(key, value);
}
public void userLogin(String userId, String password) {
CognitoUser cognitoUser = cognitoUserPool.getUser(userId);
userPassword = password;
cognitoUser.getSessionInBackground(authenticationHandler);
}
// Callback handler for the sign-in process
AuthenticationHandler authenticationHandler = new AuthenticationHandler() {
#Override
public void authenticationChallenge(ChallengeContinuation continuation) {
}
#Override
public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
if (!userSession.isValid())
Toast.makeText(context, "Rifai il login", Toast.LENGTH_SHORT).show();
else
Toast.makeText(context, "Login valido", Toast.LENGTH_SHORT).show();
//Toast.makeText(context, "Sign in success", Toast.LENGTH_LONG).show();
}
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
// The API needs user sign-in credentials to continue
AuthenticationDetails authenticationDetails = new AuthenticationDetails(userId, userPassword, null);
// Pass the user sign-in credentials to the continuation
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
// Allow the sign-in to continue
authenticationContinuation.continueTask();
}
#Override
public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) {
// Multi-factor authentication is required; get the verification code from user
//multiFactorAuthenticationContinuation.setMfaCode(mfaVerificationCode);
// Allow the sign-in process to continue
//multiFactorAuthenticationContinuation.continueTask();
}
#Override
public void onFailure(Exception exception) {
// Sign-in failed, check exception for the cause
Toast.makeText(context, "Sign in Failure " + exception.getMessage(), Toast.LENGTH_LONG).show();
}
};
public void tokenIsValid() {
CognitoUser cognitoUser = cognitoUserPool.getCurrentUser();
cognitoUser.getSessionInBackground(authenticationHandler);
}
public CognitoUserPool getCognitoUserPool() {
return cognitoUserPool;
}
}
But when I put the verification code which Cognito send me via email into a dialog:
private void showConfirmationCodeDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(signUpActivity);
LayoutInflater layoutInflater = signUpActivity.getLayoutInflater();
View dialogView = layoutInflater.inflate(R.layout.dialog_confirmation_code, null);
builder.setView(dialogView);
builder.setCancelable(false);
final EditText editTextConfirmationCode = dialogView.findViewById(R.id.edit_text_confirmation_code);
builder.setPositiveButton("Verifica", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
Toast.makeText(signUpActivity, "click " + editTextConfirmationCode.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
builder.create();
builder.show();
}
email does not get verified
I am currently working on an Android Application, and i have a problem to handle a request and execute a function just after.
The fact is my Retrofit request is in a Controller, used by a Service, and i am calling the service function inside my Activity (am i clear?).
Clearly, i have to manage one user (get and refresh access token from a webservice) and i need to be able to call my refreshToken() function and execute some code after getting and parsing the response.
This is my code :
UserActivity
public class UserActivity extends AppCompatActivity {
private final static String TAG = "UserActivity";
private User user;
private TextView textViewAccessTokenShow, textViewExpiresInShow, textViewIGPShow, textViewRefreshTokenShow;
private LoginController loginController;
private Wso2Service wso2Service, wso2ServiceIS;
boolean mBounded;
private LoginService loginService;
private Intent mIntent;
//Connection to LoginService
ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(UserActivity.this, "Service is disconnected", Toast.LENGTH_LONG).show();
mBounded = false;
loginService = null;
Log.e(TAG, "onServiceDisconnected: " );
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(UserActivity.this, "Service is connected", Toast.LENGTH_LONG).show();
mBounded = true;
LoginService.LocalBinder mLocalBinder = (LoginService.LocalBinder) service;
loginService = mLocalBinder.getServerInstance();
user = loginService.getUser();
refreshIHM();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
mIntent = new Intent(this, LoginService.class);
textViewAccessTokenShow = findViewById(R.id.textViewAccessTokenShow);
textViewRefreshTokenShow = findViewById(R.id.textViewRefreshTokenShow);
textViewExpiresInShow = findViewById(R.id.textViewExpiresInShow);
textViewIGPShow = findViewById(R.id.textViewIGPShow);
}
#Override
protected void onResume() { //Getting my user updated outside this activity and printing his informations
super.onResume();
Log.i(TAG, "onResume: ");
if(mBounded == false){
bindService(mIntent, mConnection, BIND_AUTO_CREATE);
} else {
user = loginService.getUser();
refreshIHM();
}
}
public void onClickRefreshToken(View view){
//Where i have to refresh my token, and after that executing refreshIHM()
refreshIHM();
}
public void refreshIHM(){
Log.d(TAG, "refreshIHM() called");
Log.i(TAG, "refreshIHM: "+user.toString());
textViewExpiresInShow.setVisibility(View.VISIBLE);
textViewAccessTokenShow.setVisibility(View.VISIBLE);
textViewRefreshTokenShow.setVisibility(View.VISIBLE);
textViewIGPShow.setVisibility(View.VISIBLE);
textViewAccessTokenShow.setText(user.getAccess_token());
textViewAccessTokenShow.invalidate();
textViewAccessTokenShow.requestLayout();
textViewRefreshTokenShow.setText(user.getRefresh_token());
textViewRefreshTokenShow.invalidate();
textViewRefreshTokenShow.requestLayout();
textViewExpiresInShow.setText(String.valueOf(user.getExpire_in()));
textViewExpiresInShow.invalidate();
textViewExpiresInShow.requestLayout();
textViewIGPShow.setText(user.getId_group_parent());
textViewIGPShow.invalidate();
textViewIGPShow.requestLayout();
}
}
LoginController, where i execute every functions about User data
public class LoginController {
public static final String TAG = "LOGINSERVICE";
private User usertemp;
private Wso2Service wso2Service, wso2ServiceIS;
public LoginController(){
this.wso2Service = new Retrofit.Builder()
.baseUrl(Wso2Service.APIMENDPOINT)
.addConverterFactory(ScalarsConverterFactory.create())
.build()
.create(Wso2Service.class);
this.wso2ServiceIS = new Retrofit.Builder()
.baseUrl(Wso2Service.ISENDPOINT)
.addConverterFactory(ScalarsConverterFactory.create())
.build()
.create(Wso2Service.class);
}
public User parseUserInfo(String request, User user) {
try {
JSONObject jo = new JSONObject(request);
user.setAccess_token(jo.getString("access_token"));
user.setRefresh_token(jo.getString("refresh_token"));
user.setScope(jo.getString("scope"));
user.setId_token(jo.getString("id_token"));
user.setToken_type(jo.getString("token_type"));
user.setExpire_in(jo.getInt("expires_in"));
return user;
} catch (Exception e){
Log.e(TAG, "getUserInfo: "+e.toString());
}
return null;
}
public User parseIdGroupParentInfo(String request, User user){
try {
Log.i(TAG, "parseIdGroupParentInfo: "+request);
JSONObject jo = new JSONObject(request);
user.setId_group_parent(jo.getString("id_group_parent"));
return user;
} catch (Exception e){
Log.e(TAG, "parseIdGroupParentInfo: "+e.toString());
}
return null;
}
public void refreshToken(User user){
this.usertemp = user;
Log.i(TAG, "refreshToken: ");
this.wso2Service.getTokensByRefresh("refresh_token",user.getRefresh_token(),"openid", ApiConstants.token).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()) {
//On parse la réponse
usertemp.setLogin_request_responseJSON(response.body());
parseUserInfo(response.body(), usertemp);
Log.i(TAG, "onLoginReady: " + usertemp.toString());
wso2ServiceIS.getUserInfo("Bearer "+usertemp.getAccess_token()).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
Log.i(TAG, "onResponse: "+response.code()+response.body());
usertemp = parseIdGroupParentInfo(response.body(),usertemp);
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e(TAG, "onFailure: ",t );
}
});
} else {
Log.e(TAG, "onResponse: " );
Log.e(TAG, "onResponse: Code "+response.code()+" Body : "+response.body() );
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e(TAG, "onFailure: ",t );
}
});
}
}
LoginService, what i call in every activities to use the same User everytime
public class LoginService extends Service {
public final String TAG = "LoginService";
private User user;
private LoginController loginController;
IBinder mBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
public LoginService getServerInstance() {
return LoginService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand: ");
this.user = (User)intent.getSerializableExtra("user");
Log.i(TAG, "onStartCommand: "+user.toString());
loginController = new LoginController();
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate: ");
}
#Override
public void onDestroy() {
Log.i(TAG, "onDestroy: ");
super.onDestroy();
}
public User getUser(){
Log.i(TAG, "getUser: ");
return this.user;
}
public void regenerateByRefreshToken(){
Log.d(TAG, "regenerateByRefreshToken: ");
loginController.refreshToken(user);
Log.d(TAG, "regenerateByRefreshToken: end");
}
}
Do you have any idea about how to make my RefroFit function handle its response and only after executing another function inside my UI ? Or inside my regenerateByRefreshToken() function ?
Thank you !
Do you have any idea about how to make my RefroFit function handle its
response and only after executing another function inside my UI ? Or
inside my regenerateByRefreshToken() function ?
As per the current implementation, You can achieve this using Callbacks. Create two callbacks to
Get the usertemp inside service from the controller after successful execution.
Second callback to send the user object back to activity from service
So follow below steps:
a) Create callback interface
// create new OnUserRefresh.java
public interface OnUserRefresh{
void onRefresh(User user);
void onError(Throwable t);
}
b) Modify the controller to receive the callback reference
public class LoginController {
// code...
public void refreshToken(User user, OnUserRefresh onUserRefresh){
this.usertemp = user;
Log.i(TAG, "refreshToken: ");
this.wso2Service.getTokensByRefresh("refresh_token",user.getRefresh_token(),"openid", ApiConstants.token).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()) {
//On parse la réponse
usertemp.setLogin_request_responseJSON(response.body());
parseUserInfo(response.body(), usertemp);
Log.i(TAG, "onLoginReady: " + usertemp.toString());
wso2ServiceIS.getUserInfo("Bearer "+usertemp.getAccess_token()).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
Log.i(TAG, "onResponse: "+response.code()+response.body());
usertemp = parseIdGroupParentInfo(response.body(),usertemp);
onUserRefresh.onRefresh(usertemp);
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e(TAG, "onFailure: ",t );
onUserRefresh.onError(t);
}
});
} else {
Log.e(TAG, "onResponse: " );
Log.e(TAG, "onResponse: Code "+response.code()+" Body : "+response.body() );
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e(TAG, "onFailure: ",t );
}
});
}
}
c) Pass callback object from service to controller
public class LoginService extends Service {
/*Add interface, to be used for data passing*/
public void regenerateByRefreshToken(OnUserRefresh onUserRefresh){
Log.d(TAG, "regenerateByRefreshToken: ");
loginController.refreshToken(user, new OnUserRefresh(){
#Override
void onRefresh(User user){
this.user = user;
onUserRefresh.onRefresh(user); // trigger onRefresh in client i.e. activity
}
#Override
void onError(Throwable t){
onUserRefresh.onError(t);
// log error etc
}
});
Log.d(TAG, "regenerateByRefreshToken: end");
}
}
d) Pass callback object from activity to service and implement UI updates method call
public class UserActivity extends AppCompatActivity {
public void onClickRefreshToken(View view){
//Where i have to refresh my token, and after that executing refreshIHM()
loginService.regenerateByRefreshToken(new OnUserRefresh(){
#Override
void onRefresh(User user){
this.user = user;
refreshIHM();
}
#Override
void onError(Throwable t){
// log error etc
}
});
}
}
Note: The initial user reference is always null as you are receiving it from intent in your service
this.user = (User)intent.getSerializableExtra("user");
but you are neither initialising any user object in UserActivity nor adding it in the mIntent object so you need to a user object with token and other required properties in activity for network calls.
You can optimize the flow with lambdas, Rxjava etc as well.
I have made an app in that I want to share an image and a text ,I have successfully get the login Dialog of facebook..But after Login it gives me error that Warning: Sessionless Request needs token but missing either application ID or client token.
What should i do to solve it.My code is as below ,Please help needed..
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
Session session = facebook.getSession();
if (access_token != null) {
SessionState st = SessionState.OPENED;
facebook.setAccessToken(access_token);
Exception e = new FacebookError("Error");
System.out.println("::::::::::::::aCEESS TOKEN::::::::;;"
+ access_token);
postToWall();
/*fbImageSubmit(facebook, big_img, "3sMAniquines", "Maniquines",
cat_nem, big_img);*/
onSessionStateChange(session, st, e);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (facebook.isSessionValid()) {
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
* */
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
You have to save the access token of logged user for maintaining Session for further task.
according to your code following code will give you currently logged in user's access token.
String access_token = Const.fb.getAccessToken();
I am trying to show a progress indicator when doing network requests with volley. I am getting the error "Only the original thread that create a view hierarchy can touch its views". I cannot figure out how to get my hideProgressDialog() onto the same thread as showProgressDialog(). Here's my code...
showProgressDialog("Logging you in");
String url = ApplicationController.getInstance().getBaseURL() + "Customer/LoginCustomer";
JsonRequest<String> jr = new JsonRequest<String>(Method.POST, url, jo.toString(), this.createSuccessListener(),
this.createErrorListener()) {
#Override
protected Response<String> parseNetworkResponse(NetworkResponse nr) {
hideProgressDialog();
try {
String str = new String(nr.data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
};
ApplicationController.getInstance().addToRequestQueue(jr);
}
/** Create Volley Listeners **/
private Response.ErrorListener createErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
};
}
private Response.Listener<String> createSuccessListener() {
return new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideProgressDialog();}
};
}
Solution
Thanks to tautvydas. I ended up putting these methods in my base class.
protected void showProgressDialog(String message) {
if(mHandler == null){
mHandler = new Handler();
}
if (mDialog == null || !mDialog.isShowing()) {
mDialog = new ProgressDialog(getActivity());
mDialog.setMessage(message);
mDialog.setCancelable(false);
mDialog.setIndeterminate(true);
mDialog.show();
}
}
protected void hideProgressDialog() {
if (mDialog != null) {
mHandler.post(new Runnable() {
#Override
// this will run on the main thread.
public void run() {
mDialog.hide();
}
});
}
}
Create a Handler and pass a Runnable to it to run on the main thread.
1) Declare Handler in the constructor on onCreate() method by Handler handler = new Handler(). 2) Then in your parseNetworkResponse() method call
handler.post(new Runnable() {
#Override
// this will run on the main thread.
public void run() {
hideProgressDialog();
}
});
I have done login in facebook integration and after login i want to post some message on the wall but i 'm not getting success as I am getting this error
**{Response: responseCode: 200, graphObject: null, error: {HttpStatus: 200, errorCode: 3, errorType: null, errorMessage: Unknown method}, isFromCache:false}**
my code is as follows
postbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
final Bundle params = new Bundle();
params.putString("message", "Test");
//params.putString("name", "American Virgin");
//params.putString("link", "http://bit.ly/12345");
//params.putString("description", "A Freshman College Girl on a scholarship from an ...");
//http://graph.facebook.com/100000431012652/picture?type=square
final Request postToWall = Request.newRestRequest(Session.getActiveSession(), "me/feed", params, HttpMethod.POST);
postToWall.setCallback( new Request.Callback()
{
#Override
public void onCompleted(Response response)
{
Log.i("onCompleted", response.toString());
}
});
Request.executeBatchAsync(postToWall);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("onCompletedException", e.toString());
}
}
});
}
Please suggest me.
for login i am using the below code
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());
//URL image_value = new URL("http://graph.facebook.com/"+id+"/picture?style=small" );
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"));
saveusrname = ""+user.getName().trim();
imagstring = "http://graph.facebook.com/"+""+""+user.getId()+"/picture?type=square";
// imagstring = "http://graph.facebook.com/"+""+""+user.getId()+"/picture?type=large";
//type=square
Log.i("imagstring", imagstring);
finish();
/* String username = ""+user.getName();
String Birthday = ""+user.getBirthday();
String email = ""+user.asMap().get("email");
String location = ""+user.asMap().get("location");
String gender = ""+user.asMap().get("gender");*/
new SendfacebookValue().execute(response.toString(),saveusrname.toString(),imagstring);
/*Intent i =new Intent(FacebookLogin.this, ScreenNameActivity.class);
startActivity(i);*/
/* Intent i =new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);*/
//finish();
}
}
});
}
}
});
I use this methods to post record on facebook wall. I think it will help you, check your GraphObject
private void postStatusUpdate() {
Log.d("myLogs", "Test");
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
} else {
Session.openActiveSession(this, true, statusCallback);
Log.d("myLogs", "Test 1");
final String message = "massage to post";
Request request = Request
.newStatusUpdateRequest(Session.getActiveSession(), message, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(message, response.getGraphObject(), response.getError());
}
});
request.executeAsync();
}
}
private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
String title = null;
String alertMessage = null;
if (error == null) {
title = "Success";
alertMessage = "All is good";
} else {
title = "Error";
alertMessage = error.getErrorMessage();
}
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(alertMessage)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}