I am working on an android application where user will login in app using their gmail account. I need to show list of youtube playlist of that user. I have used following code -
private String getAllPlayList() {
YouTube youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("My Project").build();
try {
HashMap<String, String> parameters = new HashMap<>();
parameters.put("part", "snippet,contentDetails");
parameters.put("mine", "true");
parameters.put("maxResults", "25");
parameters.put("onBehalfOfContentOwner", "");
parameters.put("onBehalfOfContentOwnerChannel", "");
parameters.put("key","AIzaSyASISGgWoBqDijVmzUpYCbgaWJ_ULJWdiQ");
YouTube.Playlists.List playlistsListMineRequest = youtube.playlists().list(parameters.get("part").toString());
if (parameters.containsKey("mine") && parameters.get("mine") != "") {
boolean mine = (parameters.get("mine") == "true") ? true : false;
playlistsListMineRequest.setMine(true);
}
if (parameters.containsKey("maxResults")) {
playlistsListMineRequest.setMaxResults(Long.parseLong(parameters.get("maxResults").toString()));
}
if (parameters.containsKey("onBehalfOfContentOwner") && parameters.get("onBehalfOfContentOwner") != "") {
playlistsListMineRequest.setOnBehalfOfContentOwner(parameters.get("onBehalfOfContentOwner").toString());
}
if (parameters.containsKey("onBehalfOfContentOwnerChannel") && parameters.get("onBehalfOfContentOwnerChannel") != "") {
playlistsListMineRequest.setOnBehalfOfContentOwnerChannel(parameters.get("onBehalfOfContentOwnerChannel").toString());
}
if (parameters.containsKey("key") && parameters.get("key") != "") {
playlistsListMineRequest.setKey(parameters.get("key").toString());
}
PlaylistListResponse response = playlistsListMineRequest.execute();
Log.d("PlayList",response.toString());
return response.toPrettyString();
}
catch (Exception e)
{
e.printStackTrace();
return e.getMessage().toString();
}
}
But I am getting following response -
"message" : "The request uses the mine parameter but is not properly authorized.",
Please help.
Related
I need help with my project please. I don't really have a lot to say other than that I'm trying to add payment gateway to my android app using stripe. I followed the documentation here. Towards the end where I have to test everything my app crashes and I get this error message I am almost done with this but this is the only thing in my way. Please help me. Thanks in advance
//My code is here
private void startCheckout() {
// Create a PaymentIntent by calling the sample server's /create-payment-intent endpoint.
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
String json = "{"
+ "\"currency\":\"usd\","
+ "\"items\":["
+ "{\"id\":\"photo_subscription\"}"
+ "]"
+ "}";
RequestBody body = RequestBody.create(mediaType,json);
Request request = new Request.Builder()
.url(BACKEND_URL + "create-payment-intent")
.post(body)
.build();
httpClient.newCall(request)
.enqueue(new PayCallback(this));
// Hook up the pay button to the card widget and stripe instance
Button payButton = findViewById(R.id.payButton);
payButton.setOnClickListener((View view) -> {
CardInputWidget cardInputWidget = findViewById(R.id.cardInputWidget);
PaymentMethodCreateParams params = cardInputWidget.getPaymentMethodCreateParams();
if (params != null) {
ConfirmPaymentIntentParams confirmParams = ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(params, paymentIntentClientSecret);
stripe.confirmPayment(this, confirmParams);
}
});
}
private void displayAlert(#NonNull String title,
#Nullable String message,
boolean restartDemo) {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message);
if (restartDemo) {
builder.setPositiveButton("Restart demo",
(DialogInterface dialog, int index) -> {
CardInputWidget cardInputWidget = findViewById(R.id.cardInputWidget);
cardInputWidget.clear();
startCheckout();
});
} else {
builder.setPositiveButton("Ok", null);
}
builder.create().show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Handle the result of stripe.confirmPayment
stripe.onPaymentResult(requestCode, data, new PaymentResultCallback(this));
}
private void onPaymentSuccess(#NonNull final Response response) throws IOException {
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> responseMap = gson.fromJson(
Objects.requireNonNull(response.body()).string(),
type
);
// The response from the server includes the Stripe publishable key and
// PaymentIntent details.
// For added security, our sample app gets the publishable key from the server
String stripePublishableKey = responseMap.get("publishableKey");
paymentIntentClientSecret = responseMap.get("clientSecret");
// Configure the SDK with your Stripe publishable key so that it can make requests to the Stripe API
stripe = new Stripe(
getApplicationContext(),
Objects.requireNonNull(stripePublishableKey)
);
}
private static final class PayCallback implements Callback {
#NonNull private final WeakReference<PaymentPageActivity> activityRef;
PayCallback(#NonNull PaymentPageActivity activity) {
activityRef = new WeakReference<>(activity);
}
#Override
public void onFailure(Request request, IOException e) {
final PaymentPageActivity activity = activityRef.get();
if (activity == null) {
return;
}
activity.runOnUiThread(() ->
Toast.makeText(
activity, "Error: " + e.toString(), Toast.LENGTH_LONG
).show()
);
}
#Override
public void onResponse(Response response) throws IOException {
final PaymentPageActivity activity = activityRef.get();
if (activity == null) {
return;
}
if (!response.isSuccessful()) {
activity.runOnUiThread(() ->
Toast.makeText(
activity, "Error: " + response.toString(), Toast.LENGTH_LONG
).show()
);
} else {
activity.onPaymentSuccess(response);
}
}
}
private static final class PaymentResultCallback
implements ApiResultCallback<PaymentIntentResult> {
#NonNull private final WeakReference<PaymentPageActivity> activityRef;
PaymentResultCallback(#NonNull PaymentPageActivity activity) {
activityRef = new WeakReference<>(activity);
}
#Override
public void onSuccess(#NonNull PaymentIntentResult result) {
final PaymentPageActivity activity = activityRef.get();
if (activity == null) {
return;
}
PaymentIntent paymentIntent = result.getIntent();
PaymentIntent.Status status = paymentIntent.getStatus();
if (status == PaymentIntent.Status.Succeeded) {
// Payment completed successfully
Gson gson = new GsonBuilder().setPrettyPrinting().create();
activity.displayAlert(
"Payment completed",
gson.toJson(paymentIntent),
true
);
} else if (status == PaymentIntent.Status.RequiresPaymentMethod) {
// Payment failed – allow retrying using a different payment method
activity.displayAlert(
"Payment failed",
Objects.requireNonNull(paymentIntent.getLastPaymentError()).getMessage(),
false
);
}
}
#Override
public void onError(#NonNull Exception e) {
final PaymentPageActivity activity = activityRef.get();
if (activity == null) {
return;
}
// Payment request failed – allow retrying using the same payment method
activity.displayAlert("Error", e.toString(), false);
}
}
int this line
Map<String, String> responseMap = gson.fromJson(
Objects.requireNonNull(response.body()).string(),
type
);
you shold pass a json Object not a String, use GSON to fix it
something like that :
Gson g = new Gson();
Foo f = g.fromJson(jsonString, bar.class)
Overall skeleton of the app goes like this,
The app opens, let's the new user to register or already existing user to login goes into SQLite. Later I want to fetch data from/through the user's profile. Is it possible?
I have been looking into this AccessToken stuff offered by Fb but everything flows over my head.
Let's say the user logs in initially by registering. Later I'll let the user to type in what to search and I want to fetch those search result from Facebook, those search results should also be from the user's profile. All these should happen even without the user manually entering his Fb details, rather he's going to get a pop up dialog box that says Continue with Fb login something of that sort.
Facebook user details only access with Access Token which is generated by facebook. First need to create developer account then create app over developer account. App ID and Key need to put on your android app which you can get from facebook developer account after creating an app there. For more details check out its official documentation.
I assume you question states that you want to get the user detail from facebook without getting logged in you app.if that is the case yes it is possible. because getting details from facebook is a different process and you getting logged in your app is a different one.
private Context context;
private Fragment mFragment;
private ShareDialog mShareDialog;
/**
* #param context
*/
public FacebookLoginManager(Context context, Fragment fragment) {
this.context = context;
this.mFragment = fragment;
}
/**
* #param context
*/
public FacebookLoginManager(Context context) {
this.context = context;
}
/**
* The purpose of this method is to initialize the facebook sdk
*
* #param callbackManager
*/
public void initializedFacebook(CallbackManager callbackManager) {
if (FacebookSdk.isInitialized()) {
performFacebookLogin(callbackManager);
} else {
FacebookSdk.sdkInitialize(getApplicationContext());
performFacebookLogin(callbackManager);
}
}
/**
* The purpose of this method is to initialize the facebook data from the server
*
* #param callbackManager
*/
private void performFacebookLogin(CallbackManager callbackManager) {
try {
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
final String accessToken = "" + loginResult.getAccessToken().getToken();
Log.e("accessToken", accessToken);
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
final FacebookResponseBean mFacebookResponseBean = new FacebookResponseBean();
if (object != null) {
if (object.has(FacebookConstants.ID) && object.get(FacebookConstants.ID) != null) {
mFacebookResponseBean.setUserId(object.get(FacebookConstants.ID) + "");
}
if (object.has(FacebookConstants.NAME) && object.get(FacebookConstants.NAME) != null) {
mFacebookResponseBean.setName(object.get(FacebookConstants.NAME) + "");
}
if (object.has(FacebookConstants.EMAIL) && object.get(FacebookConstants.EMAIL) != null) {
mFacebookResponseBean.setEmail(object.get(FacebookConstants.EMAIL) + "");
}
if (object.has(FacebookConstants.GENDER) && object.get(FacebookConstants.GENDER) != null) {
mFacebookResponseBean.setGender(object.get(FacebookConstants.GENDER) + "");
}
if (object.has(FacebookConstants.BIRTHDAY) && object.get(FacebookConstants.BIRTHDAY) != null) {
mFacebookResponseBean.setBirthday(object.get(FacebookConstants.BIRTHDAY) + "");
}
if (object.has(FacebookConstants.AGE_RANGE) && object.get(FacebookConstants.AGE_RANGE) != null) {
mFacebookResponseBean.setAgerange(object.get(FacebookConstants.AGE_RANGE) + "");
}
if (object.has(FacebookConstants.TIMEZONE) && object.get(FacebookConstants.TIMEZONE) != null) {
mFacebookResponseBean.setTimezone(object.get(FacebookConstants.TIMEZONE) + "");
}
if (object.has(FacebookConstants.VERIFIED) && object.get(FacebookConstants.VERIFIED) != null) {
mFacebookResponseBean.setVerified(object.get(FacebookConstants.VERIFIED) + "");
}
if (object.has(FacebookConstants.UPDATED_TIME) && object.get(FacebookConstants.UPDATED_TIME) != null) {
mFacebookResponseBean.setUpdatedtime(object.get(FacebookConstants.UPDATED_TIME) + "");
}
if (object.has(FacebookConstants.LOCALE) && object.get(FacebookConstants.LOCALE) != null) {
mFacebookResponseBean.setLocale(object.get(FacebookConstants.LOCALE) + "");
}
if (object.has(FacebookConstants.FIRST_NAME) && object.get(FacebookConstants.FIRST_NAME) != null) {
mFacebookResponseBean.setFirstName(object.get(FacebookConstants.FIRST_NAME) + "");
}
if (object.has(FacebookConstants.LAST_NAME) && object.get(FacebookConstants.LAST_NAME) != null) {
mFacebookResponseBean.setLastName(object.get(FacebookConstants.LAST_NAME) + "");
}
if (object.has(FacebookConstants.PICTURE) && object.get(FacebookConstants.PICTURE) != null) {
JSONObject picture = object.getJSONObject(FacebookConstants.PICTURE);
JSONObject data = picture.getJSONObject("data");
if (data.has("url") && data.get("url") != null) {
mFacebookResponseBean.setPhotolink(data.get("url") + "");
Logger.error("image", data.get("url") + "");
}
}
}
if (context instanceof LoginActivity) {
((LoginActivity) context).setFaceBookResponse(mFacebookResponseBean);
} else if (context instanceof RegistrationActivity) {
((RegistrationActivity) context).setFaceBookResponse(mFacebookResponseBean);
} else if (context instanceof UserProfileActivity) {
((UserProfileActivity) context).setFaceBookResponse(mFacebookResponseBean);
} else if (mFragment != null && mFragment instanceof FragmentLinkAccounts) {
((FragmentLinkAccounts) mFragment).setFaceBookResponse(mFacebookResponseBean);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", FacebookConstants.PERMISSION);
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
exception.printStackTrace();
if (exception instanceof FacebookAuthorizationException) {
if (AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* The purpose of this method is to share the image and content on facebook
*
* #param activity
* #param manager
* #param image
* #param isShareRequest
* #param id
*/
public void shareContent(final Activity activity, CallbackManager manager, View image, final boolean isShareRequest, int id) {
mShareDialog = new ShareDialog(activity);
String time = GlobalAcess.getDateTime();
mShareDialog.registerCallback(manager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
if (isShareRequest)
ToastMessage.getInstance(activity).showLongMessage(activity.getString(R.string.msg_request_posted));
else
ToastMessage.getInstance(activity).showLongMessage(activity.getString(R.string.msg_trip_posted));
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
error.printStackTrace();
}
});
String url = "";
if (isShareRequest) {
url = NetworkConstants.SHARE_REQUEST_URL + "id=" + id + "?t=" + time;
} else {
url = NetworkConstants.SHARE_TRIP_URL + "id=" + id + "?t=" + time;
}
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse(url))
.build();
mShareDialog.show(content);
}
}
}
//
is it possible to get all of my users without adding them to through contacts. My problem is that I store users in Firebase and they can have invisible profile. I need to get only users with visible profiles. How can I achieve this?
Thanks
You can use the below method code for getting all the user users .You need to pass the users of set type then you will get the response in if(!TextUtils.isEmpty(response)){
public String postUserDetailsByUserIds(Set<String> userIds) {
try {
HttpRequestUtils httpRequestUtils = new HttpRequestUtils(this);
final String userDetailsUrl = "https://apps.applozic.com/rest/ws/user/detail";
if (userIds !=null && userIds.size()>0 ) {
List<String> userDetailsList = new ArrayList<>();
String response = "";
int count = 0;
for (String userId : userIds) {
count++;
userDetailsList.add(userId);
if( count% 60==0){
UserDetailListFeed userDetailListFeed = new UserDetailListFeed();
userDetailListFeed.setContactSync(true);
userDetailListFeed.setUserIdList(userDetailsList);
String jsonFromObject = GsonUtils.getJsonFromObject(userDetailListFeed, userDetailListFeed.getClass());
Log.i(TAG,"Sending json:" + jsonFromObject);
response = httpRequestUtils.postData(userDetailsUrl + "?contactSync=true", "application/json", "application/json", jsonFromObject);
userDetailsList = new ArrayList<String>();
if(!TextUtils.isEmpty(response)){
List<UserDetail> userDetails = (List<UserDetail>) GsonUtils.getObjectFromJson(response, new TypeToken<List<UserDetail>>() {}.getType());
for (UserDetail userDetail : userDetails) {
//Here you will get the user details
Log.i("UserDeatil","userId:"+userDetail.getUserId()) ;
Log.i("UserDeatil","display name:"+userDetail.getDisplayName()) ;
Log.i("UserDeatil","image link:"+userDetail.getImageLink()) ;
Log.i("UserDeatil","phone number:"+userDetail.getPhoneNumber()) ;
}
}
}
}
if(!userDetailsList.isEmpty()&& userDetailsList.size()>0) {
UserDetailListFeed userDetailListFeed = new UserDetailListFeed();
userDetailListFeed.setContactSync(true);
userDetailListFeed.setUserIdList(userDetailsList);
String jsonFromObject = GsonUtils.getJsonFromObject(userDetailListFeed, userDetailListFeed.getClass());
response = httpRequestUtils.postData(userDetailsUrl + "?contactSync=true", "application/json", "application/json", jsonFromObject);
Log.i(TAG, "User details response is :" + response);
if (TextUtils.isEmpty(response) || response.contains("<html>")) {
return null;
}
if (!TextUtils.isEmpty(response)) {
List<UserDetail> userDetails = (List<UserDetail>) GsonUtils.getObjectFromJson(response, new TypeToken<List<UserDetail>>() {}.getType());
for (UserDetail userDetail : userDetails) {
//Here you will get the user details
Log.i("UserDeatil","userId:"+userDetail.getUserId()) ;
Log.i("UserDeatil","display name:"+userDetail.getDisplayName()) ;
Log.i("UserDeatil","image link:"+userDetail.getImageLink()) ;
Log.i("UserDeatil","phone number:"+userDetail.getPhoneNumber()) ;
} }
}
return response;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I have researched for > 15 hours about this problem:
I am building a Hybrid App , I login with the Volley Framework (native View),
as soon as I login I fetch the response Header,extract the Cookie and save it into my sharedprefs. After successful login I have a native mainscreen that contains links to several Webviews,
how do I pass the Cookie I received from the login into the Webview?
90% of the Answers on the Internet use CookieSyncManager, which is deprecated.
I tried the java.net.CookieManager also, nothing of it works.
Here's my Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebView = new WebView(this);
setContentView(mWebView);
cookies = pref.getString(Const.COOKIE_KEY,"null");
userID = pref.getString(Const.USER_ID_KEY,"null");
mUrl = Const.PERFORMANCE_WEBVIEW_LINK + Const.USER_ID;
String cookieText = Const.COOKIE_KEY + "=" + cookies;
//Approach A Environment for the Cookies
//Does not work
cookieSync = CookieSyncManager.createInstance(this);
cookieManager = CookieManager.getInstance();
cookieManager.removeSessionCookie();
cookieManager.setCookie(mUrl, cookieText);
cookieSync.sync();
SystemClock.sleep(10000);
/*APPROACH B, sending the Cookies with header
##Did not Work##
final Map<String, String> headers = new HashMap<>();
Log.d("cookie", cookieText);
headers.put("Cookie",cookieText);
*/
if(cookies.equals("null") || userID.equals("null")) {
Toast.makeText(PerformanceWebview.this, "Error", Toast.LENGTH_SHORT).show();
//Logging Out
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
else {
//mWebView.loadUrl(mUrl,headers);
mWebView.loadUrl(mUrl);
Toast.makeText(PerformanceWebview.this,cookieText, Toast.LENGTH_SHORT).show();
Log.d("URL", "URL: " + mUrl);
}
}
I also tried passing a WebClient to the WebView and overrode it's shouldOverrideURl method and passed the headers into it.
Another approach I did was using WebSettings and passing a ChromeClient..
None of the Answers here seem to work
First make sure Volley uses cookies: ( see https://stackoverflow.com/a/21271347 )
// Make volley remember cookies
// Do this only once on app startup, and keep the reference to the cookiemanager.
// I'm saving it on an App class, but you can do something different.
App.cookieManager = new CookieManager();
CookieHandler.setDefault(App.cookieManager);
// Note, we are using the java.net.CookieManager above.
Then, after for example a login call in Volley, sync the cookies to WebView:
// Sync cookies to webview
android.webkit.CookieManager webkitCookies = android.webkit.CookieManager.getInstance();
for (HttpCookie cookie : App.cookieManager.getCookieStore().getCookies()) {
webkitCookies.setCookie(cookie.getDomain(), cookie.getName() + "=" + cookie.getValue());
}
if (Build.VERSION.SDK_INT >= 21) {
webkitCookies.flush();
} else {
CookieSyncManager.getInstance().sync();
}
class CookieStore_ implements CookieStore{
/** this map may have null keys! */
private final Map<URI, List<HttpCookie>> map = new HashMap<URI, List<HttpCookie>>();
private android.webkit.CookieManager manager;
public CookieStore_() {
manager = android.webkit.CookieManager.getInstance();
}
public synchronized void add(URI uri, HttpCookie cookie) {
if (cookie == null) {
throw new NullPointerException("cookie == null");
}
uri = cookiesUri(uri);
//add cookie to the CookieManager,be sure you have called
//CookieSyncManager.createInstance(context) if your android version
//is lower than Lollipop
manager.setCookie(uri.toString(),cookie.toString());
List<HttpCookie> cookies = map.get(uri);
if (cookies == null) {
cookies = new ArrayList<HttpCookie>();
map.put(uri, cookies);
} else {
cookies.remove(cookie);
}
cookies.add(cookie);
}
private URI cookiesUri(URI uri) {
if (uri == null) {
return null;
}
try {
return new URI("http", uri.getHost(), null, null);
} catch (URISyntaxException e) {
return uri; // probably a URI with no host
}
}
public synchronized List<HttpCookie> get(URI uri) {
if (uri == null) {
throw new NullPointerException("uri == null");
}
List<HttpCookie> result = new ArrayList<HttpCookie>();
// get cookies associated with given URI. If none, returns an empty list
List<HttpCookie> cookiesForUri = map.get(uri);
if (cookiesForUri != null) {
for (Iterator<HttpCookie> i = cookiesForUri.iterator(); i.hasNext(); ) {
HttpCookie cookie = i.next();
if (cookie.hasExpired()) {
i.remove(); // remove expired cookies
} else {
result.add(cookie);
}
}
}
// get all cookies that domain matches the URI
for (Map.Entry<URI, List<HttpCookie>> entry : map.entrySet()) {
if (uri.equals(entry.getKey())) {
continue; // skip the given URI; we've already handled it
}
List<HttpCookie> entryCookies = entry.getValue();
for (Iterator<HttpCookie> i = entryCookies.iterator(); i.hasNext(); ) {
HttpCookie cookie = i.next();
if (!HttpCookie.domainMatches(cookie.getDomain(), uri.getHost())) {
continue;
}
if (cookie.hasExpired()) {
i.remove(); // remove expired cookies
} else if (!result.contains(cookie)) {
result.add(cookie);
}
}
}
return Collections.unmodifiableList(result);
}
public synchronized List<HttpCookie> getCookies() {
List<HttpCookie> result = new ArrayList<HttpCookie>();
for (List<HttpCookie> list : map.values()) {
for (Iterator<HttpCookie> i = list.iterator(); i.hasNext(); ) {
HttpCookie cookie = i.next();
if (cookie.hasExpired()) {
i.remove(); // remove expired cookies
} else if (!result.contains(cookie)) {
result.add(cookie);
}
}
}
return Collections.unmodifiableList(result);
}
public synchronized List<URI> getURIs() {
List<URI> result = new ArrayList<URI>(map.keySet());
result.remove(null); // sigh
return Collections.unmodifiableList(result);
}
public synchronized boolean remove(URI uri, HttpCookie cookie) {
if (cookie == null) {
throw new NullPointerException("cookie == null");
}
List<HttpCookie> cookies = map.get(cookiesUri(uri));
if (cookies != null) {
return cookies.remove(cookie);
} else {
return false;
}
}
public synchronized boolean removeAll() {
boolean result = !map.isEmpty();
map.clear();
return result;
}
public void clearCookies(){
map.clear();
}
}
this class was copied from CookieStoreImpl and added a android.webkit.CookieManager in it,when add(URI uri, HttpCookie cookie) get called, add the cookie to the cookieManager,then when webview load a url which has a match in cookieManager,webview add matched cookies to the request's headers.
below is a helper class
public class CookieUtil {
private CookieManager manager;
private CookieStore_ cookieStore_;
private CookieSyncManager syncManager;
private static CookieUtil cookieUtil;
private boolean isInitialed = false;
private CookieUtil(Context context) {
manager = CookieManager.getInstance();
if (!Util.hasLollipop()){
syncManager = CookieSyncManager.createInstance(context);
}
cookieStore_ = new CookieStore_();
}
public void clearCookies(){
if (manager.hasCookies()){
if (Util.hasLollipop()){
manager.removeAllCookies(null);
}else {
manager.removeAllCookie();
}
}
cookieStore_.clearCookies();
}
public static CookieUtil getCookieUtil(Context context){
if (cookieUtil == null)
cookieUtil = new CookieUtil(context);
return cookieUtil;
}
public void sync(){
if (Util.hasLollipop()){
manager.flush();
}else {
syncManager.sync();
}
}
public void setThirdPartyCookieAcceptable(WebView webView){
if (Util.hasLollipop()){
manager.setAcceptThirdPartyCookies(webView,true);
}
}
public void initCookieHandler(){
if (isInitialed)
return;
isInitialed = true;
CookieHandler.setDefault(new java.net.CookieManager(cookieStore_, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
}
}
if you don't need to save cookies to local storage,you can share volley cookies to webview through a single line
CookieUtil.getCookieUtil(context).initCookieHandler();
and don't forget to call clearCookies() when logout
I did the login using Google Identity Toolkit, I have noticed that the class GitkitUser.UserProfile retrieves the photo url, but is too small. The google documentation do not say anything about photo size.
https://developers.google.com/identity/toolkit/android/reference/com/google/identitytoolkit/GitkitUser.UserProfile.html#getPhotoUrl()
For example with Facebook login, the getPhotoUrl() method returns:
https://scontent.xx.fbcdn.net/hprofile-xap1/v/t1.0-1/p50x50/12651146_10208004779813340_3124516205553866664_n.jpg?oh=efa817d10aaf9d184a767bae81a71071&oe=576850AD
For example with Gmail login, the getPhotoUrl() method returns:
https://lh6.googleusercontent.com/-5XFRyKHh7Os/AAAAAAAAAAI/AAAAAAAABIo/Trf7GjTnFec/s96-c/photo.jpg
Deleting /s96-c (or replace to /s200-c) in the Gmail photo url appears big, but I need a workaround to Facebook photo.
The solution for android was obtain the federatedId and after that call:
http://graph.facebook.com/{federatedId}/picture?type=large
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
client = GitkitClient.newBuilder(this, new GitkitClient.SignInCallbacks() {
#Override
public void onSignIn(IdToken idToken, GitkitUser user) {
DataStorage.getInstance().setLastToken(idToken.getTokenString());
Configuration config = Configuration.fromMetaData(AppInfo.getAppInfo(LoginActivity.this).metaData);
ApiClient apiClient = new ApiClient(config.getApiKey(), AppInfo.getAppInfo(LoginActivity.this), config.getServerWidgetUrl());
final GetAccountInfo.Request request = apiClient.newGetAccountInfoRequest(idToken);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
GetAccountInfo.Response accountInfo = request.execute();
JSONArray users = accountInfo.getJsonResponse().optJSONArray("users");
JSONObject user = users == null ? null : users.optJSONObject(0);
String email = user == null ? null : user.optString("email");
if (email != null) {
JSONArray providerUserInfo = user.optJSONArray("providerUserInfo");
if (providerUserInfo != null && providerUserInfo.length() != 0) {
for (int i = 0; i < providerUserInfo.length(); ++i) {
JSONObject userInfo = providerUserInfo.optJSONObject(i);
if (userInfo != null) {
try {
String userInfoString = userInfo.getString("federatedId");
if(userInfoString.contains("facebook.com")) {
int lastSlash = userInfoString.lastIndexOf("/");
if(lastSlash != -1) {
String federatedIdFacebook = userInfoString.substring(lastSlash + 1, userInfoString.length());
Log.i("federatedIdFacebook", federatedIdFacebook);
}
break;
}
} catch (JSONException e) {
Log.e("LoginActivity", e.getMessage());
}
}
}
}
}
return null;
}
}.execute();
}
#Override
public void onSignInFailed() {
Toast.makeText(LoginActivity.this, "Sign in failed", Toast.LENGTH_LONG).show();
}
}).build();
}
You could use the idToken to get the User's identifier at IDP (facebook id).
See users[].providerUserInfo[].federatedId at https://developers.google.com/identity/toolkit/web/reference/relyingparty/getAccountInfo
And then use the facebookId to get the large account picture, with
http://graph.facebook.com/{facebookId}/picture?type=large