I am trying to implement facebook login and wall post in Android, so I created a non-activity class that handles everything. I saw all these examples where they use this method - onActivityResult but I don't know if I have to use it or why it's so important. Code works without it as long as I don't have the facebook app installed on the phone and I wonder if onActivityResult have anything to do with it. PS: I'm pretty sure I generated the hash key corectly. Thank you. :)
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.infobest.praiser.R;
import com.infobest.praiser.utils.Constants;
/**
* Functionality for facebook sharing
*
* #author oana_balaceanu
*
*/
public class ShareFacebook
{
private static final String[] PERMISSIONS = new String[] {"publish_stream"};
private Facebook facebook;
private String messageToPost;
private Context ctx;
public ShareFacebook(String messageToPost, Context ctx)
{
this.messageToPost = messageToPost;
this.ctx = ctx;
}
public boolean saveCredentials(Facebook facebook)
{
Editor editor = ctx.getSharedPreferences(Constants.KEY, Context.MODE_PRIVATE).edit();
editor.putString(Constants.TOKEN, facebook.getAccessToken());
editor.putLong(Constants.EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
public boolean restoreCredentials(Facebook facebook)
{
SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.KEY,
Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(Constants.TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(Constants.EXPIRES, 0));
return facebook.isSessionValid();
}
public void share()
{
facebook = new Facebook(Constants.APP_ID);
restoreCredentials(facebook);
if (!facebook.isSessionValid())
{
loginAndPostToWall();
}
else
{
postToWall(messageToPost);
}
}
public void loginAndPostToWall()
{
facebook.authorize((Activity) ctx, PERMISSIONS,
(DialogListener) new LoginDialogListener());
}
public void postToWall(String message)
{
FacebookPoster fp = new FacebookPoster();
fp.execute(message, null, null);
}
private class FacebookPoster extends AsyncTask<String, Object, Object>
{
#Override
protected Object doInBackground(String... message)
{
Bundle parameters = new Bundle();
parameters.putString("message", message[0]);
parameters.putString("link", ctx.getResources().getString(R.string.rateLink));
parameters.putString("picture", ctx.getResources().getString(R.string.linkIconPicture));
try
{
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") || response.equals("false"))
{
return ctx.getResources().getString(R.string.facebookError);
}
else
{
return ctx.getResources().getString(R.string.facebookSuccess);
}
}
catch (Exception e)
{
Log.d("ShareOnFacebook", e.toString());
return ctx.getResources().getString(R.string.facebookError);
}
}
#Override
protected void onPostExecute(Object result)
{
super.onPostExecute(result);
showToast(result);
}
}
class LoginDialogListener implements DialogListener
{
public void onComplete(Bundle values)
{
saveCredentials(facebook);
if (messageToPost != null)
{
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error)
{
showToast(ctx.getResources().getString(R.string.facebookError));
}
public void onError(DialogError error)
{
showToast(ctx.getResources().getString(R.string.facebookError));
}
public void onCancel()
{
showToast(ctx.getResources().getString(R.string.facebookCancel));
}
}
private void showToast(Object message)
{
Toast.makeText(ctx, message.toString(), Toast.LENGTH_SHORT).show();
}
}
If you test your app on emulator or smartphone with installed Facebook app, login will fail because of it.
Related
package kr.phpdev.call;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.PhoneNumberUtils;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class PhoneStateReceiver extends BroadcastReceiver {
static String mLastState;
static final String TAG = "Call Manager";
final OkHttpClient client = new OkHttpClient();
#Override
public void onReceive(Context context, Intent intent) {
CallReceivedChk(context, intent);
}
private void CallReceivedChk(Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
String mState = String.valueOf(state);
if (mState.equals(mLastState)) { // 두번 호출되는 문제 해결 목적
return;
} else {
mLastState = mState;
}
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d(TAG, "CALL_IDLE");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d(TAG, "CALL_OFFHOOK");
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "CALL_RINGING >>> " + PhoneNumberUtils.formatNumber(incomingNumber));
RequestBody formBody = new FormBody.Builder()
.add("pn", PhoneNumberUtils.formatNumber(incomingNumber))
.build();
final Request request = new Request.Builder()
.url("http://phpdev.kr/cm/logsend.php")
.post(formBody)
.build();
AsyncTask<String, String, String> asyncTask = new AsyncTask<String, String, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
return null;
}
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != "FAILED") {
Log.d(TAG, s);
Toast.makeText(getApplicationContext(), "토스트메시지입니다.", Toast.LENGTH_SHORT).show();
}
}
};
asyncTask.execute();
break;
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
}
}
how can i get toast message?
You need to do that on onPostExecute since it is running on the UI thread. And also in Java string comparison is like s.equals("Failed"):
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (!s.equals("FAILED")) {
Log.d(TAG, s);
Toast.makeText(context, "토스트메시지입니다.", Toast.LENGTH_SHORT).show();
}
}
Use Toast.makeText(context, "토스트메시지입니다.",Toast.LENGTH_SHORT).show();`
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != "FAILED") {
Log.d(TAG, s);
Toast.makeText(context, "토스트메시지입니다.", Toast.LENGTH_SHORT).show();
}
}
Error:(103, 68) error: local variable context is accessed from within inner class; needs to be declared final. You just need using "context" instead of "getApplicationContext()".
I am using telegram API to develop my application. Here is the whole code.
app_info.java:
package com.example.mytelegram;
import org.telegram.api.engine.AppInfo;
public class app_info extends AppInfo {
public app_info(int apiId, String deviceModel, String systemVersion,
String appVersion, String langCode) {
super(apiId, deviceModel, systemVersion, appVersion, langCode);
// TODO Auto-generated constructor stub
}
MemoryApiState.java:
package com.example.mytelegram;
import org.telegram.api.TLConfig;
import org.telegram.api.TLDcOption;
import org.telegram.api.engine.storage.AbsApiState;
import org.telegram.mtproto.state.AbsMTProtoState;
import org.telegram.mtproto.state.ConnectionInfo;
import org.telegram.mtproto.state.KnownSalt;
import java.util.ArrayList;
import java.util.HashMap;
public class MemoryApiState implements AbsApiState {
private HashMap<Integer, ConnectionInfo[]> connections = new HashMap<Integer, ConnectionInfo[]>();
private HashMap<Integer, byte[]> keys = new HashMap<Integer, byte[]>();
private HashMap<Integer, Boolean> isAuth = new HashMap<Integer, Boolean>();
private int primaryDc = 2; // I have tested application with primaryDc=0 to 10
public MemoryApiState(boolean isTest) {
connections.put(1, new ConnectionInfo[]{
new ConnectionInfo(1, 0, isTest ? "149.154.167.40" : "149.154.167.50", 443)
});
}
#Override
public synchronized int getPrimaryDc() {
return primaryDc;
}
#Override
public synchronized void setPrimaryDc(int dc) {
primaryDc = dc;
}
#Override
public synchronized boolean isAuthenticated(int dcId) {
if (isAuth.containsKey(dcId)) {
return isAuth.get(dcId);
}
return false;
}
#Override
public synchronized void setAuthenticated(int dcId, boolean auth) {
isAuth.put(dcId, auth);
}
#Override
public synchronized void updateSettings(TLConfig config) {
connections.clear();
HashMap<Integer, ArrayList<ConnectionInfo>> tConnections = new HashMap<Integer, ArrayList<ConnectionInfo>>();
int id = 0;
for (TLDcOption option : config.getDcOptions()) {
if (!tConnections.containsKey(option.getId())) {
tConnections.put(option.getId(), new ArrayList<ConnectionInfo>());
}
tConnections.get(option.getId()).add(new ConnectionInfo(id++, 0, option.getIpAddress(), option.getPort()));
}
for (Integer dc : tConnections.keySet()) {
connections.put(dc, tConnections.get(dc).toArray(new ConnectionInfo[0]));
}
}
#Override
public synchronized byte[] getAuthKey(int dcId) {
return keys.get(dcId);
}
#Override
public synchronized void putAuthKey(int dcId, byte[] key) {
keys.put(dcId, key);
}
#Override
public synchronized ConnectionInfo[] getAvailableConnections(int dcId) {
if (!connections.containsKey(dcId)) {
return new ConnectionInfo[0];
}
return connections.get(dcId);
}
#Override
public synchronized AbsMTProtoState getMtProtoState(final int dcId) {
return new AbsMTProtoState() {
private KnownSalt[] knownSalts = new KnownSalt[0];
#Override
public byte[] getAuthKey() {
return MemoryApiState.this.getAuthKey(dcId);
}
#Override
public ConnectionInfo[] getAvailableConnections() {
return MemoryApiState.this.getAvailableConnections(dcId);
}
#Override
public KnownSalt[] readKnownSalts() {
return knownSalts;
}
#Override
protected void writeKnownSalts(KnownSalt[] salts) {
knownSalts = salts;
}
};
}
#Override
public synchronized void resetAuth() {
isAuth.clear();
}
#Override
public synchronized void reset() {
isAuth.clear();
keys.clear();
}
}
MainActivity.java:
package com.example.mytelegram;
import java.io.IOException;
import org.telegram.api.TLAbsUpdates;
import org.telegram.api.TLConfig;
import org.telegram.api.TLNearestDc;
import org.telegram.api.auth.TLAuthorization;
import org.telegram.api.auth.TLSentCode;
import org.telegram.api.engine.ApiCallback;
import org.telegram.api.engine.AppInfo;
import org.telegram.api.engine.LoggerInterface;
import org.telegram.api.engine.RpcException;
import org.telegram.api.engine.TelegramApi;
import org.telegram.api.requests.TLRequestAuthSendCall;
import org.telegram.api.requests.TLRequestAuthSendCode;
import org.telegram.api.requests.TLRequestAuthSignIn;
import org.telegram.api.requests.TLRequestHelpGetConfig;
import org.telegram.api.requests.TLRequestHelpGetNearestDc;
import org.telegram.api.requests.TLRequestUpdatesGetState;
import org.telegram.api.updates.TLState;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends ActionBarActivity {
static Context context;
private static AppInfo ai;
private static void createApi() throws IOException {
String res = "No test";
boolean useTest = res.equals("test");
apiState = new MemoryApiState(useTest);
ai=new AppInfo(App_ID, "Sony", "???", "???", "en");
api = new TelegramApi(apiState, ai, new ApiCallback() {
#Override
public void onAuthCancelled(TelegramApi api) {
}
#Override
public void onUpdatesInvalidated(TelegramApi api) {
}
#Override
public void onUpdate(TLAbsUpdates updates) {
Log.d("tlg", "onUpdate(TLAbsUpdates updates)");
}
});
}
private static void login() throws IOException {
//TLNearestDc dcInfo = api.doRpcCallNonAuth(new TLRequestHelpGetNearestDc());
// api.switchToDc(dcInfo.getNearestDc());
//************ Exception raises here ************
TLConfig config = api.doRpcCallNonAuth(new TLRequestHelpGetConfig()); // I have An IOException Here (e=timeout Exception)
apiState.updateSettings(config);
Log.d("tlg","completed.");
String phone = "+9891********"; // I have tested app with the phone without plus too
Log.d("tlg","Sending sms to phone " + phone + "...");
TLSentCode sentCode = null;
try {
api.doRpcCallNonAuth(new TLRequestAuthSendCode(phone, 1, app_id, "__hash__", "en"));
} catch (RpcException e) {
if (e.getErrorCode() == 303) {
int destDC;
if (e.getErrorTag().startsWith("NETWORK_MIGRATE_")) {
destDC = Integer.parseInt(e.getErrorTag().substring("NETWORK_MIGRATE_".length()));
} else if (e.getErrorTag().startsWith("PHONE_MIGRATE_")) {
destDC = Integer.parseInt(e.getErrorTag().substring("PHONE_MIGRATE_".length()));
} else if (e.getErrorTag().startsWith("USER_MIGRATE_")) {
destDC = Integer.parseInt(e.getErrorTag().substring("USER_MIGRATE_".length()));
} else {
throw e;
}
api.switchToDc(destDC);
sentCode = api.doRpcCallNonAuth(new TLRequestAuthSendCode(phone, 0, app_id, "__hash__", "en"));
} else {
throw e;
}
}
Log.d("tlg","Activation code:");
String code = "123";
TLAuthorization auth = api.doRpcCallNonAuth(new TLRequestAuthSignIn(phone, sentCode.getPhoneCodeHash(), code));
apiState.setAuthenticated(apiState.getPrimaryDc(), true);
Log.d("tlg","Activation complete.");
TLState state = api.doRpcCall(new TLRequestUpdatesGetState());
Log.d("tlg","loaded.");
}
static MemoryApiState apiState;
static TelegramApi api;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=getApplicationContext();
try {
createApi();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
login();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//workLoop();
}
}
I have added telegram-api library (telegram-api-1.1.127-shadow.jar) in my eclipse 'libs' folder. The problem is Timeout Exception in MainActivity.java when I want to call RPC. Where is the problem? What should I do? My OS is windows 8.1 . I am searching for 2 whole days. I have read github codes too. They are very complicated for me. I can not figure out what should I do?
I have added INTERNET and ACCESS_NETWORK_STATE permisions to AndroidManifest.xml. I allways check the network connection when my application runs.
I found the problem in your code:
In MemoryApiState you should put, in the 'connections' map, 'primaryDc' as key and not '1'.
i made login and signup with Facebook functionality in my app,the problem is that once user clicks log in with Facebook button and dialog appears for login if user cancel that dialog it is redirected to login and from that if it again clicks on log in with Facebook white screen appears..Log cat shows error as "an attempt was made to open a session that has a pending request" below is my code..i am confused about this error any help is appriciated
FaceBookIntegration.java
/**
*
*/
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
;
/**
* Facebook integration class ccontains login with fb and share activity
*
* #author Admin
*/
public class FacebookIntegration extends GlobalActivity implements ResponseListener {
private ProgressDialog progressDialog;
private Session session;
private boolean share;
private UserHistory userHistory = null;
Preferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = HWUtil.getPreferences(this);
share = getIntent().getBooleanExtra(HWUtil.SHARE, false);
if (share) {
userHistory = preferences.getShareUserHistory();
if (Validator.isNull(userHistory)) {
finish();
}
}
Session.StatusCallback statusCallback = new SessionStatusCallback();
session = Session.getActiveSession();
if (session == null) {
session = new Session(this);
Session.setActiveSession(session);
}
if (!session.isOpened() && !session.isClosed()) {
session.openForPublish(new Session.OpenRequest(this).setPermissions(Arrays.asList("public_profile", "email", "publish_actions", "user_actions.fitness")).setCallback(statusCallback));
} else {
if (share) {
shareOnFacebook();
} else {
getProfileDetail(session);
}
}
}
/**
* Share activity records on facebook
*/
private void shareOnFacebook() {
if (Validator.isNotNull(userHistory)) {
String apiUrl;
if ("Running".equals(userHistory.getSportName())) {
apiUrl = "fitness.runs";
} else if ("Walking".equals(userHistory.getSportName())) {
apiUrl = "fitness.walks";
} else if ("Cycling".equals(userHistory.getSportName())) {
apiUrl = "fitness.bikes";
} else {
apiUrl = "*:sport";
}
Bundle params = new Bundle();
params.putString("course", com.aimdek.healthwel.network.Request.HOST_URL + "/user-history/" + userHistory.getUserId() + "/" + userHistory.getId());
params.putBoolean("fb:explicitly_shared", true);
/* make the API call */
new Request(Session.getActiveSession(), "/me/" + apiUrl, params, HttpMethod.POST, new Request.Callback() {
public void onCompleted(Response response) {
if (response.getError() == null) {
com.aimdek.healthwel.network.Request.getRequest().sendRequest(com.aimdek.healthwel.network.Request.SHARE_USER_HISTORY, FacebookIntegration.this, FacebookIntegration.this, RequestParameterBuilder.buildMapForShareUserHistory(userHistory.getId(), FacebookIntegration.this));
} else {
finish();
Log.d("Facebook error", response.getError().toString());
}
}
}).executeAsync();
if (Validator.isNotNull(userHistory.getHistoryPictures()) && userHistory.getHistoryPictures().length > 0) {
for (int i = 0; i < userHistory.getHistoryPictures().length; i++) {
HistoryPictures pictures = userHistory.getHistoryPictures()[i];
String message = getString(R.string.facebook_status, HWUtil.getFullName(preferences.getUserInfo().getFirstName(), preferences.getUserInfo().getLastName()), userHistory.getSportName());
params.putString("message", message);
if (Validator.isNotNull(pictures.getPictureUrl())) {
params.putString("url", pictures.getPictureUrl());
} else {
params.putByteArray("picture", Base64.decode(pictures.getData(), Base64.DEFAULT));
// params.putString("method", "photos.upload");
}
new Request(Session.getActiveSession(), "/me/photos", params, HttpMethod.POST, new Request.Callback() {
public void onCompleted(Response response) {
if (response.getError() == null) {
} else {
}
}
}).executeAsync();
}
}
}
}
#Override
public void onResponse(int type, Object... result) {
if (type == Request.SHARE_USER_HISTORY) {
preferences.setShareOnFacebook(false);
if (preferences.isShareOnGoogle()) {
Intent intent = new Intent(FacebookIntegration.this, GooglePlusIntegration.class);
intent.putExtra(HWUtil.SHARE, true);
startActivity(intent);
} else {
preferences.setShareUserHistory(null);
}
} else {
if (Validator.isNotNull(result) && result.length > 0 && Validator.isNotNull(result[0])) {
String response = (String) result[0];
HWUtil.loadMainActivity(response, FacebookIntegration.this);
}
}
finish();
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
if (share) {
shareOnFacebook();
} else {
getProfileDetail(session);
}
}
}
}
/**
* get facebook profile detail
*
* #param session - pass facebook session
*/
private void getProfileDetail(Session session) {
showProgressDialog();
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (Validator.isNotNull(user)) {
UserInfo userInfoDto = new UserInfo();
String id = user.getId();
userInfoDto.setFirstName(user.getFirstName());
userInfoDto.setLastName(user.getLastName());
String email = Validator.isNotNull(user.asMap().get("email")) ? user.asMap().get("email").toString() : HWUtil.BLANK;
if (Validator.isNotNull(email)) {
userInfoDto.setEmail(email);
String gender = Validator.isNotNull(user.asMap().get("gender")) ? user.asMap().get("gender").toString() : HWUtil.BLANK;
if ("male".equals(gender)) {
userInfoDto.setGender(1);
} else {
userInfoDto.setGender(2);
}
userInfoDto.setUniqueId(HWUtil.getDeviceId(FacebookIntegration.this));
userInfoDto.setMeasureUnit(HWUtil.getMeasureUnit(FacebookIntegration.this));
userInfoDto.setPassword(HWUtil.BLANK);
String imageURL = "https://graph.facebook.com/" + id + "/picture?type=large";
userInfoDto.setProfilePictureUrl(imageURL);
Request.getRequest().sendJsonRequest(Request.UPDATE_USER, FacebookIntegration.this, FacebookIntegration.this, RequestParameterBuilder.buildJsonObjectFromUserInfo(userInfoDto));
dismissProgressDialog();
} else {
HWUtil.showToast(FacebookIntegration.this, getString(R.string.allow_read_email));
dismissProgressDialog();
finish();
return;
}
}
}
}).executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (session != null && !session.isOpened()) {
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
} else {
finish();
}
super.onActivityResult(requestCode, resultCode, data);
}
private void showProgressDialog() {
if(!isFinishing() && progressDialog==null) {
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.show();
}
}
/**
* dismiss Progress Dialog.
*/
private void dismissProgressDialog() {
if (!isFinishing() &&progressDialog!=null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
I am working on an Android app which uses sessions by managing cookies from an API based on magento backend.
On the app side, I am using Volley Library for network request. I have successfully got the network response and from that I have fetched the "Set-Cookie" value. Now when I am attaching this cookie to the header but the server doesn't validate my session.
The strange thing is I tried to request the same JSON request from a rest client and then used the cookie from that and added to the header as a static value and then I was provided session access. I completely have no idea regarding what is going on. Why the cookies from rest client is working while the cookie value from my network response doesn't.
Here is my SignIn Activity code where I am doing a login json request and storing the cookie value.
package com.paaltao.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.github.mrengineer13.snackbar.SnackBar;
import com.paaltao.R;
import com.paaltao.classes.MyApp;
import com.paaltao.classes.PersistentCookieStore;
import com.paaltao.classes.ProgressWheel;
import com.paaltao.classes.SharedPreferenceClass;
import com.paaltao.logging.L;
import com.paaltao.network.VolleySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static com.paaltao.extras.Keys.UserCredentials.*;
import static com.paaltao.extras.urlEndPoints.BASE_URL;
import static com.paaltao.extras.urlEndPoints.LOGIN;
import static com.paaltao.extras.urlEndPoints.UAT_BASE_URL;
public class SignInActivity extends AppCompatActivity {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
Button SignUpBtn;
Button SignInBtn;
ProgressWheel progressBar;
EditText email, password;
TextView forgotPassword;
String emailId,accessToken,api_ver,token,firstName,lastName,cookie,newCookie;
Boolean login_success;
SharedPreferenceClass preferenceClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
Toolbar toolbar = (Toolbar) this.findViewById(R.id.app_bar);
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setBackgroundColor(getResources().getColor(R.color.transparent));
this.setSupportActionBar(toolbar);
this.setTitle("Sign in");
initiate();
onItemClick();
}
public void initiate() {
SignUpBtn = (Button) findViewById(R.id.signUpBtn);
email = (EditText) findViewById(R.id.email_field);
password = (EditText) findViewById(R.id.password_field);
SignInBtn = (Button) findViewById(R.id.signInBtn);
forgotPassword = (TextView) findViewById(R.id.forgot_password);
progressBar = (ProgressWheel)findViewById(R.id.action_progress);
preferenceClass = new SharedPreferenceClass(getApplicationContext());
}
public boolean validationCheck() {
if (email.getText().toString().length() == 0)
email.setError("Please provide your email. Your email must be in the format abc#xyz.com");
else if (password.getText().toString().length() == 0)
password.setError("Please provide a password");
else return true;
return false;
}
public void onItemClick() {
SignInBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validationCheck()) {
sendJsonRequest();
}
}
});
SignUpBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SignInActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SignInActivity.this, ForgotPasswordActivity.class);
startActivity(intent);
}
});
}
public static String getRequestUrl() {
return UAT_BASE_URL
+ LOGIN;
}
public void sendJsonRequest() {
progressBar.setVisibility(View.VISIBLE);
final JSONObject jsonObject = new JSONObject();
final JSONObject signIn = new JSONObject();
try {
jsonObject.put("email", email.getText().toString());
jsonObject.put("password", password.getText().toString());
signIn.put("emailSignIn", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, getRequestUrl(), signIn, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
parseJSONResponse(jsonObject);
//Calling the Snackbar
Log.e("response", jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
new SnackBar.Builder(SignInActivity.this)
.withMessage("No Internet Connection!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
}) {
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
// MyApp.get().checkSessionCookie(response.headers);
L.m(response.headers.toString());
L.m(Arrays.toString(response.data));
L.m(response.headers.get("Set-Cookie"));
preferenceClass.saveCookiee(response.headers.get("Set-Cookie"));
cookie = response.headers.get("Set-Cookie");
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
newCookie = splitSessionId[1];
//cookie = response.headers.values().toString();
Log.e("split",newCookie);
preferenceClass.saveCookie(newCookie);
return super.parseNetworkResponse(response);
}
#Override
public Map<String, String> getHeaders ()throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
// MyApp.get().addSessionCookie(headers);
return headers;
}
}
;
requestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject jsonObject) {
if (jsonObject == null || jsonObject.length() == 0) {
return;
}
try {
JSONObject dataObject = jsonObject.getJSONObject(KEY_DATA);
JSONObject signInObject = dataObject.getJSONObject(KEY_SIGN_IN);
JSONObject accessTokenObject = signInObject.getJSONObject(KEY_ACCESS_TOKEN);
JSONObject errorNodeObject = dataObject.getJSONObject(KEY_ERROR_NODE);
if(dataObject.has(KEY_VENDOR)){
if (dataObject.isNull(KEY_VENDOR)){
return;
}
else {JSONObject vendorObject = dataObject.getJSONObject(KEY_VENDOR);
if(vendorObject != null){
String vendor_login = vendorObject.getString(KEY_HAS_SHOP);
if(vendor_login != null && vendor_login.contains("true")){
preferenceClass.saveVendorLoginSuccess(vendor_login);
}}}
}
emailId = signInObject.getString(KEY_EMAIL);
firstName = signInObject.getString(KEY_FIRST_NAME);
lastName = signInObject.getString(KEY_LAST_NAME);
login_success = signInObject.getBoolean(KEY_USER_LOGIN_SUCCESS);
preferenceClass.saveFirstName(firstName);
preferenceClass.saveLastName(lastName);
preferenceClass.saveUserEmail(emailId);
if(accessTokenObject.has(KEY_TOKEN)){
token = accessTokenObject.getString(KEY_TOKEN);}
String errorCode = errorNodeObject.getString(KEY_ERROR_CODE);
String message = errorNodeObject.getString(KEY_MESSAGE);
if (login_success){
Log.e("TAG",login_success.toString());
if (token!= null && token.length()!=0){
preferenceClass.saveAccessToken(token);
preferenceClass.saveUserEmail(emailId);
Intent intent = new Intent(SignInActivity.this,HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
else{
Log.e("TAG",login_success.toString());
new SnackBar.Builder(SignInActivity.this)
.withMessage("Username or Password is Incorrect!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
and this is the code for the fragment where I am doing a check session test with the stored cookie received from network response (Note: I replaced the cookie with the one I got from rest client and it worked!!)
package com.paaltao.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpClientStack;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.HttpStack;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.github.mrengineer13.snackbar.SnackBar;
import com.paaltao.R;
import com.paaltao.activity.AddressActivity;
import com.paaltao.activity.IntroPageActivity;
import com.paaltao.activity.PaaltaoInfo;
import com.paaltao.activity.EditProfileActivity;
import com.paaltao.classes.MyApp;
import com.paaltao.classes.PersistentCookieStore;
import com.paaltao.classes.SharedPreferenceClass;
import com.paaltao.logging.L;
import com.paaltao.network.VolleySingleton;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import cn.pedant.SweetAlert.SweetAlertDialog;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ACCESS_TOKEN;
import static com.paaltao.extras.Keys.UserCredentials.KEY_DATA;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ERROR_CODE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ERROR_NODE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_MESSAGE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_SIGN_OUT;
import static com.paaltao.extras.urlEndPoints.BASE_URL;
import static com.paaltao.extras.urlEndPoints.SIGN_OUT;
import static com.paaltao.extras.urlEndPoints.UAT_BASE_URL;
//This is a user account fragment.
public class AccountFragment extends Fragment {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
RelativeLayout accountLink,my_address,signOut;
View view;
String accessToken;
TextView firstName,lastName,about,terms,privacy,notificationSettings;
SharedPreferenceClass preferenceClass;
SweetAlertDialog dialog;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_account, container, false);
initialize();
onItemClick();
return view;
}
public static String getRequestUrl() {
return UAT_BASE_URL
+ SIGN_OUT;
}
public void sendJsonRequest(){
final JSONObject jsonObject = new JSONObject();
final JSONObject signOut = new JSONObject();
try{
jsonObject.put("accessToken","67drd56g");
signOut.put("signOut", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,getRequestUrl(),signOut,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("error", jsonObject.toString());
Log.e("json", signOut.toString());
parseJSONResponse(jsonObject);
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
new SnackBar.Builder(getActivity())
.withMessage("No Internet Connection!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
});
requestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject jsonObject) {
if (jsonObject == null || jsonObject.length() == 0) {
return;
}
try {
JSONObject dataObject = jsonObject.getJSONObject(KEY_DATA);
JSONObject signOutObject = jsonObject.getJSONObject(KEY_SIGN_OUT);
JSONObject errorNodeObject = dataObject.getJSONObject(KEY_ERROR_NODE);
accessToken = signOutObject.getString(KEY_ACCESS_TOKEN);
String errorCode = errorNodeObject.getString(KEY_ERROR_CODE);
String message = errorNodeObject.getString(KEY_MESSAGE);
if (errorCode.equals("200")){
preferenceClass.clearAccessToken();
preferenceClass.clearFirstName();
preferenceClass.clearLastName();
preferenceClass.clearUserEmail();
Log.e("accessToken",accessToken);
Intent intent = new Intent(getActivity(),IntroPageActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
getActivity().finish();
}
else{
new SnackBar.Builder(getActivity())
.withMessage("Error in signing out")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void sendJsonRequest1(){
final JSONObject jsonObject = new JSONObject();
final JSONObject sessionCheck = new JSONObject();
try{
jsonObject.put("accessToken","67drd56g");
sessionCheck.put("checkSession", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,getRequestUrl1(),sessionCheck,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("error", jsonObject.toString());
Log.e("json", sessionCheck.toString());
Log.e("url",getRequestUrl());
L.m(jsonObject.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
})
{
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
// MyApp.get().checkSessionCookie(response.headers);
//L.m(response.headers.toString());
return super.parseNetworkResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
String sessionId = preferenceClass.getCookie();
Log.e("cOOOKIE","frontend="+sessionId);
Log.e("sessionid","frontend=7fgenogpffjvvmdg1gf439hta7");
// headers.put(COOKIE_KEY,"frontend="+sessionId);
headers.put(COOKIE_KEY,"frontend=e7qfldgsnf7aop381a8vk3b866");
return headers;
}};
requestQueue.add(jsonObjectRequest);
}
private String getRequestUrl1() {
return UAT_BASE_URL+"checkSession";
}
public void initialize(){
accountLink = (RelativeLayout)view.findViewById(R.id.account_link);
my_address = (RelativeLayout)view.findViewById(R.id.my_address);
signOut = (RelativeLayout)view.findViewById(R.id.signOut);
preferenceClass = new SharedPreferenceClass(getActivity());
firstName = (TextView)view.findViewById(R.id.firstName);
lastName = (TextView)view.findViewById(R.id.lastName);
about = (TextView)view.findViewById(R.id.about);
terms = (TextView)view.findViewById(R.id.terms);
privacy = (TextView)view.findViewById(R.id.privacy);
if(preferenceClass.getFirstName() != null)
firstName.setText(preferenceClass.getFirstName());
if(preferenceClass.getLastName() != null)
lastName.setText(preferenceClass.getLastName());
notificationSettings = (TextView)view.findViewById(R.id.notification_settings);
}
public void onItemClick(){
notificationSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendJsonRequest1();
}
});
accountLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), EditProfileActivity.class));
}
});
my_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), AddressActivity.class));
}
});
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
confirmSignOut();
}
});
about.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","about_paaltao");
startActivity(intent);
}
});
terms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","terms");
startActivity(intent);
}
});
privacy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","privacy_policy");
startActivity(intent);
}
});
}
public void confirmSignOut(){
dialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.NORMAL_TYPE);
dialog.setTitleText("Signout")
.setContentText("Are you sure you want to sign out?")
.setConfirmText("Yes")
.setCancelText("No")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sendJsonRequest();
}
})
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
dialog.cancel();
}
})
.show();
}
}
There is no structural difference between the rest client cookie and the one recieved in app:
rest client cookie : frontend=48b1i38fgls4d0241mp6d6rrr0
app side cookie : frontend=86n349m3patu37eud00ntobd90
Thanks in advance. It will be a life saver if some one can help.
We are trying to access skydrive using phonegap.We used an activity to call login function of skydrive. But it does not call login function at all.
Would be great help if someone shed light on this.
Here is the code.
Here activity is called from plugin class of phonegap
Intent i = new Intent(myac, DispAct.class);
try{
System.out.println("before start activity");
//i.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
// i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
( this.cordova.getActivity()).startActivity(i);
}
catch(Exception e){ System.out.println("in catch"+e);}
Below code is the called activity
package org.apache.cordova;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveStatus;
import com.microsoft.live.R;
public class DispAct extends Activity
{
log obj;
private Object cordova;
private static final String APP_CLIENT_ID ="00000000400D893E" ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("disp on create");
}
#Override
protected void onStart() {
super.onStart();
System.out.println("disp on start");
obj=new log();
obj.auth = new LiveAuthClient(this.getApplicationContext(), APP_CLIENT_ID);
Iterable<String> scopes = Arrays.asList("wl.basic","wl.signin","wl.skydrive","wl.skydrive_update");
obj.auth.login(this,scopes,obj);//********this is the function which has to call login page but does not work
System.out.println("disp after login");
}
#Override
public void onResume()
{
super.onResume();
//finish();
}
}
final class log implements LiveAuthListener{
String type,message;
LiveConnectClient client;
LiveAuthClient auth;
//Parcel out;
public log()
{
//auth=new LiveAuthClient(this, message);
}
synchronized public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
if(status == LiveStatus.CONNECTED) {
// this.resultTextView.setText("Signed in.");
System.out.println("IN SUCCess");
client = new LiveConnectClient(session);
//download(0);
notify();
}
else {
//this.resultTextView.setText("Not signed in.");
type="ERROR";
message="Not Connected";
client = null;
System.out.println("IN complete err");
notify();
}
}
synchronized public void onAuthError(LiveAuthException exception, Object userState) {
//this.resultTextView.setText("Error signing in: " + exception.getMessage());
client = null;
//type="ERROR";
//message="Error logging in";
System.out.println("IN error");
notify();
}
}
Here activity is displayed but login page does not appear which should appear as the result of login function