Example usage for android.accounts AccountManager getUserData

List of usage examples for android.accounts AccountManager getUserData

Introduction

In this page you can find the example usage for android.accounts AccountManager getUserData.

Prototype

public String getUserData(final Account account, final String key) 

Source Link

Document

Gets the user data named by "key" associated with the account.

Usage

From source file:me.philio.ghost.ui.PostsFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle args = getArguments();/* w ww . j  a v  a  2  s.  c o  m*/
    if (args != null) {
        if (args.containsKey(ARG_ACCOUNT)) {
            mAccount = args.getParcelable(ARG_ACCOUNT);
        }
        if (args.containsKey(ARG_SHOW)) {
            mShow = args.getInt(ARG_SHOW);
        }
    }

    // Set up list adapater
    String[] from = new String[] { "image", "title", "published_at" };
    int[] to = new int[] { R.id.img_post, R.id.txt_title, R.id.txt_subtitle };
    mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.item_post, null, from, to, 0);
    mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            Post post = new Post();
            post.loadFromCursor(cursor);
            switch (view.getId()) {
            // If post image exists replace placeholder
            case R.id.img_post:
                BezelImageView imageView = (BezelImageView) view;
                if (post.image != null) {
                    try {
                        String path = ImageUtils.getUrl(post.blog, post.image);
                        String filename = ImageUtils.getFilename(getActivity(), mBlog, path);
                        File cover = new File(filename);
                        if (cover.exists()) {
                            Picasso.with(getActivity()).load(cover).fit().centerCrop().into(imageView);
                        }
                    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
                        Log.e(TAG, "Error loading image");
                    }
                } else {
                    imageView.setImageResource(R.drawable.ic_action_action_description);
                }
                return true;
            // Format the subtitle like on the web admin
            case R.id.txt_subtitle:
                TextView textView = (TextView) view;
                if (post.status == Post.Status.DRAFT) {
                    textView.setTextColor(getResources().getColor(R.color.red));
                    textView.setText(R.string.post_draft);
                    return true;
                } else if (post.page) {
                    textView.setTextColor(getResources().getColor(R.color.grey));
                    textView.setText(R.string.post_page);
                    return true;
                } else {
                    textView.setTextColor(getResources().getColor(R.color.grey));
                    textView.setText(getString(R.string.post_published_ago,
                            DateUtils.format(getActivity(), post.publishedAt)));
                    return true;
                }
            }
            return false;
        }
    });
    setListAdapter(mAdapter);

    // Get current blog
    AccountManager accountManager = AccountManager.get(getActivity());
    String blogUrl = accountManager.getUserData(mAccount, KEY_BLOG_URL);
    String email = accountManager.getUserData(mAccount, KEY_EMAIL);
    mBlog = DatabaseUtils.getBlog(blogUrl, email);

    // Load posts
    getLoaderManager().initLoader(LOADER_LIST, null, this);
}

From source file:org.klnusbaum.udj.network.PlayerCommService.java

private void joinPlayer(Intent intent, AccountManager am, Account account, boolean attemptReauth) {
    if (!Utils.isNetworkAvailable(this)) {
        doLoginFail(am, account, PlayerJoinError.NO_NETWORK_ERROR);
        return;// ww w  .j a  va  2 s. c o  m
    }

    String userId = am.getUserData(account, Constants.USER_ID_DATA);
    String playerId = intent.getStringExtra(Constants.PLAYER_ID_EXTRA);
    String ownerId = intent.getStringExtra(Constants.PLAYER_OWNER_ID_EXTRA);
    if (userId.equals(ownerId)) {
        setLoggedInToPlayer(intent, am, account, playerId);
        return;
    }

    String authToken;
    String password = "";
    boolean hasPassword = false;
    //TODO hanle error if account isn't provided
    try {
        //TODO handle if player id isn't provided
        authToken = am.blockingGetAuthToken(account, "", true);
        if (intent.hasExtra(Constants.PLAYER_PASSWORD_EXTRA)) {
            Log.d(TAG, "password given for player");
            hasPassword = true;
            password = intent.getStringExtra(Constants.PLAYER_PASSWORD_EXTRA);
        } else {
            Log.d(TAG, "No password given for player");
        }
    } catch (OperationCanceledException e) {
        Log.e(TAG, "Operation canceled exception");
        doLoginFail(am, account, PlayerJoinError.AUTHENTICATION_ERROR);
        return;
    } catch (AuthenticatorException e) {
        Log.e(TAG, "Authenticator exception");
        doLoginFail(am, account, PlayerJoinError.AUTHENTICATION_ERROR);
        return;
    } catch (IOException e) {
        Log.e(TAG, "IO exception");
        doLoginFail(am, account, PlayerJoinError.AUTHENTICATION_ERROR);
        return;
    }

    try {
        if (!hasPassword) {
            ServerConnection.joinPlayer(playerId, authToken);
        } else {
            ServerConnection.joinPlayer(playerId, password, authToken);
        }
        setLoggedInToPlayer(intent, am, account, playerId);
    } catch (IOException e) {
        Log.e(TAG, "IO exception when joining player");
        Log.e(TAG, e.getMessage());
        doLoginFail(am, account, PlayerJoinError.SERVER_ERROR);
    } catch (JSONException e) {
        Log.e(TAG, "JSON exception when joining player");
        Log.e(TAG, e.getMessage());
        doLoginFail(am, account, PlayerJoinError.SERVER_ERROR);
    } catch (AuthenticationException e) {
        handleLoginAuthException(intent, am, account, authToken, attemptReauth);
    } catch (PlayerInactiveException e) {
        Log.e(TAG, "Player inactive Exception when joining player");
        doLoginFail(am, account, PlayerJoinError.PLAYER_INACTIVE_ERROR);
    } catch (ParseException e) {
        e.printStackTrace();
        doLoginFail(am, account, PlayerJoinError.SERVER_ERROR);
    } catch (PlayerPasswordException e) {
        Log.e(TAG, "Player Password Exception");
        e.printStackTrace();
        doLoginFail(am, account, PlayerJoinError.PLAYER_PASSWORD_ERROR);
    } catch (PlayerFullException e) {
        Log.e(TAG, "Player Password Exception");
        e.printStackTrace();
        doLoginFail(am, account, PlayerJoinError.PLAYER_FULL_ERROR);
    } catch (BannedException e) {
        Log.e(TAG, "Player Password Exception");
        e.printStackTrace();
        doLoginFail(am, account, PlayerJoinError.BANNED_ERROR);
    }
}

From source file:dev.drsoran.moloko.sync.SyncAdapter.java

private Pair<String, String> getCredentials(Account account) {
    final AccountManager accountManager = AccountManager.get(context);

    final String apiKey = accountManager.getUserData(account, Constants.FEAT_API_KEY);
    final String sharedSecret = accountManager.getUserData(account, Constants.FEAT_SHARED_SECRET);

    return Pair.create(apiKey, sharedSecret);
}

From source file:com.ubuntuone.android.files.activity.LoginActivity.java

/**
 * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
 *//*from   www  .  ja v  a2  s.  c  o  m*/
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.fragment_content);

    final Intent intent = getIntent();
    if (intent == null) {
        Log.e(TAG, "This activity intended to be instantiated via an Intent.");
        finish();
        return;
    }

    mAccountAuthenticatorResponse = intent
            .getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
    if (mAccountAuthenticatorResponse != null) {
        mAccountAuthenticatorResponse.onRequestContinued();
    }

    int fragmentToShow = FRAGMENT_SIGN_IN_OR_UP;

    final String action = intent.getAction();
    if (ACTION_VALIDATE.equals(action) && savedInstanceState == null) {
        showValidateFragment(true);
        return;
    }

    final AccountManager accountManager = AccountManager.get(this);
    final Account account = Preferences.getAccount(accountManager);
    if (account != null && savedInstanceState == null) {
        fragmentToShow = FRAGMENT_SIGN_IN;
        final String hint = accountManager.getUserData(account, Constants.KEY_AUTHTOKEN_HINT);
        final String oauthData = accountManager.peekAuthToken(account, Constants.AUTH_TOKEN_TYPE);
        if (oauthData == null && hint != null) {
            fragmentToShow = FRAGMENT_VALIDATE;
        } else if (oauthData != null && mAccountAuthenticatorResponse != null) {
            UIUtil.showToast(this, R.string.sso_only_one_supported, true);
            finish();
            return;
        }
    }

    if (savedInstanceState != null) {
        // Android will re-add the fragment automatically.
        return;
    }

    switch (fragmentToShow) {
    case FRAGMENT_VALIDATE:
        showValidateFragment(false);
        break;
    case FRAGMENT_SIGN_IN_OR_UP:
        showSignInOrUpFragment();
        break;
    case FRAGMENT_SIGN_IN:
        ChangeLogUtils.maybeShowChangelog(this);
        showSignInFragment(false);
        break;

    default:
        break;
    }
}

From source file:org.klnusbaum.udj.network.EventCommService.java

private void leaveEvent(AccountManager am, Account account, boolean attemptReauth) {
    Log.d(TAG, "In leave event");

    if (account == null) {
        //TODO handle error
        return;//  w w w.j a v a 2  s .  c o  m
    }

    long userId;
    String authToken;
    try {
        userId = Long.valueOf(am.getUserData(account, Constants.USER_ID_DATA));
        //TODO handle if event id isn't provided
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (OperationCanceledException e) {
        Log.e(TAG, "Operation canceled exception in EventCommService");
        return;
    } catch (AuthenticatorException e) {
        Log.e(TAG, "Authenticator exception in EventCommService");
        return;
    } catch (IOException e) {
        Log.e(TAG, "IO exception in EventCommService");
        return;
    }

    try {
        long eventId = Long.valueOf(am.getUserData(account, Constants.LAST_EVENT_ID_DATA));
        if (eventId != Constants.NO_EVENT_ID) {
            ServerConnection.leaveEvent(eventId, Long.valueOf(userId), authToken);
            setNotInEvent(account);
            Intent leftEventIntent = new Intent(Constants.LEFT_EVENT_ACTION);
            sendBroadcast(leftEventIntent);
        }
    } catch (IOException e) {
        Log.e(TAG, "IO exception in EventCommService: " + e.getMessage());
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            Log.e(TAG, "Soft Authentication exception in EventCommService");
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            leaveEvent(am, account, false);
        } else {
            Log.e(TAG, "HARD Authentication exception in EventCommService");
        }
    } finally {
        //TODO potential this get's repeated because it's already called once
        //above. I'll deal with that fact later.
        setNotInEvent(account);
    }
    //TODO need to implement exponential back off when log out fails.
    // 1. This is just nice to the server
    // 2. If we don't log out, there could be problems on the next event joined
}

From source file:com.owncloud.android.ui.fragment.FileDetailActivitiesFragment.java

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    file = getArguments().getParcelable(ARG_FILE);
    account = getArguments().getParcelable(ARG_ACCOUNT);

    if (savedInstanceState != null) {
        file = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
        account = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
    }//  w  ww.  java  2 s  .co  m

    View view = inflater.inflate(R.layout.file_details_activities_fragment, container, false);
    unbinder = ButterKnife.bind(this, view);

    setupView();

    onCreateSwipeToRefresh(swipeEmptyListRefreshLayout);
    onCreateSwipeToRefresh(swipeListRefreshLayout);

    fetchAndSetData(null);

    swipeListRefreshLayout.setOnRefreshListener(() -> onRefreshListLayout(swipeListRefreshLayout));
    swipeEmptyListRefreshLayout.setOnRefreshListener(() -> onRefreshListLayout(swipeEmptyListRefreshLayout));

    AccountManager accountManager = AccountManager.get(getContext());
    userId = accountManager.getUserData(account,
            com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID);

    callback = new VersionListInterface.CommentCallback() {

        @Override
        public void onSuccess() {
            commentInput.getText().clear();
            fetchAndSetData(null);
        }

        @Override
        public void onError(int error) {
            Snackbar.make(recyclerView, error, Snackbar.LENGTH_LONG).show();
        }
    };

    commentInput.getBackground().setColorFilter(ThemeUtils.primaryAccentColor(getContext()),
            PorterDuff.Mode.SRC_ATOP);

    return view;
}

From source file:org.klnusbaum.udj.network.EventCommService.java

private void enterEvent(Intent intent, AccountManager am, Account account, boolean attemptReauth) {
    if (!Utils.isNetworkAvailable(this)) {
        doLoginFail(am, account, EventJoinError.NO_NETWORK_ERROR);
        return;/*w w w .j  av a2s  .com*/
    }

    long userId, eventId;
    String authToken;
    //TODO hanle error if account isn't provided
    try {
        userId = Long.valueOf(am.getUserData(account, Constants.USER_ID_DATA));
        //TODO handle if event id isn't provided
        authToken = am.blockingGetAuthToken(account, "", true);
        eventId = intent.getLongExtra(Constants.EVENT_ID_EXTRA, Constants.NO_EVENT_ID);
    } catch (OperationCanceledException e) {
        Log.e(TAG, "Operation canceled exception in EventCommService");
        doLoginFail(am, account, EventJoinError.AUTHENTICATION_ERROR);
        return;
    } catch (AuthenticatorException e) {
        Log.e(TAG, "Authenticator exception in EventCommService");
        doLoginFail(am, account, EventJoinError.AUTHENTICATION_ERROR);
        return;
    } catch (IOException e) {
        Log.e(TAG, "IO exception in EventCommService");
        doLoginFail(am, account, EventJoinError.AUTHENTICATION_ERROR);
        return;
    }

    try {
        ServerConnection.joinEvent(eventId, userId, authToken);
        setEventData(intent, am, account);
        ContentResolver cr = getContentResolver();
        UDJEventProvider.eventCleanup(cr);
        HashMap<Long, Long> previousRequests = ServerConnection.getAddRequests(userId, eventId, authToken);
        UDJEventProvider.setPreviousAddRequests(cr, previousRequests);
        JSONObject previousVotes = ServerConnection.getVoteRequests(userId, eventId, authToken);
        UDJEventProvider.setPreviousVoteRequests(cr, previousVotes);
        Intent joinedEventIntent = new Intent(Constants.JOINED_EVENT_ACTION);
        am.setUserData(account, Constants.LAST_EVENT_ID_DATA, String.valueOf(eventId));
        am.setUserData(account, Constants.EVENT_STATE_DATA, String.valueOf(Constants.IN_EVENT));
        sendBroadcast(joinedEventIntent);
    } catch (IOException e) {
        Log.e(TAG, "IO exception when joining event");
        Log.e(TAG, e.getMessage());
        doLoginFail(am, account, EventJoinError.SERVER_ERROR);
    } catch (JSONException e) {
        Log.e(TAG, "JSON exception when joining event");
        Log.e(TAG, e.getMessage());
        doLoginFail(am, account, EventJoinError.SERVER_ERROR);
    } catch (AuthenticationException e) {
        handleLoginAuthException(intent, am, account, authToken, attemptReauth);
    } catch (EventOverException e) {
        Log.e(TAG, "Event Over Exception when joining event");
        //Log.e(TAG, e.getMessage());
        doLoginFail(am, account, EventJoinError.EVENT_OVER_ERROR);
    } catch (AlreadyInEventException e) {
        Log.e(TAG, "Already In Event Exception when joining event");
        try {
            ServerConnection.leaveEvent(e.getEventId(), userId, authToken);
            enterEvent(intent, am, account, true);
        } catch (AuthenticationException f) {
            handleLoginAuthException(intent, am, account, authToken, attemptReauth);
        } catch (IOException f) {
            Log.e(TAG, "IO exception when attempting to leave one event before " + "joining another");
            Log.e(TAG, f.getMessage());
            doLoginFail(am, account, EventJoinError.SERVER_ERROR);
        }
    }
}

From source file:eu.trentorise.smartcampus.ac.authenticator.AMSCAccessProvider.java

@Override
public UserData readUserData(Context ctx, String inAuthority) {
    AccountManager am = AccountManager.get(ctx);
    Account account = new Account(Constants.getAccountName(ctx), Constants.getAccountType(ctx));
    //      final String authority = inAuthority == null ? Constants.AUTHORITY_DEFAULT : inAuthority;
    //      String token = am.peekAuthToken(account, authority);
    //      if (token == null) return null;
    String userDataString = am.getUserData(account, AccountManager.KEY_USERDATA);
    if (userDataString == null)
        return null;
    try {//from  w w  w.ja  va2s.  co  m
        return UserData.valueOf(new JSONObject(userDataString));
    } catch (JSONException e) {
        return null;
    }
}

From source file:eu.trentorise.smartcampus.ac.authenticator.AMSCAccessProvider.java

@Override
public String promote(final Activity activity, String inAuthority, final String token) {
    final String authority = inAuthority == null ? Constants.AUTHORITY_DEFAULT : inAuthority;
    final AccountManager am = AccountManager.get(activity);
    //      Bundle options = new Bundle();
    //      if (token != null) {
    //         options.putString(Constants.PROMOTION_TOKEN, token);
    //      }//from  w w w.jav  a2  s  . c  o m
    final Account a = new Account(Constants.getAccountName(activity), Constants.getAccountType(activity));
    final String userDataString = am.getUserData(a, AccountManager.KEY_USERDATA);

    invalidateToken(activity, authority);

    am.getAuthToken(new Account(Constants.getAccountName(activity), Constants.getAccountType(activity)),
            authority, null, null, new AccountManagerCallback<Bundle>() {
                @Override
                public void run(AccountManagerFuture<Bundle> result) {
                    Bundle bundle = null;
                    try {
                        bundle = result.getResult();
                        Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT);
                        if (launch != null) {
                            launch.putExtra(Constants.KEY_AUTHORITY, authority);
                            launch.putExtra(Constants.PROMOTION_TOKEN, token);
                            launch.putExtra(Constants.OLD_DATA, userDataString);
                            activity.startActivityForResult(launch, SC_AUTH_ACTIVITY_REQUEST_CODE);
                        } else if (bundle.getString(AccountManager.KEY_AUTHTOKEN) != null) {
                            //                         am.setAuthToken(a, authority, bundle.getString(AccountManager.KEY_AUTHTOKEN));
                            //                         am.addAccountExplicitly(a, null, null);
                            // no token acquired
                        } else {
                            storeAnonymousToken(token, authority, am, a);
                        }
                    } catch (Exception e) {
                        // revert the invalidated token
                        storeAnonymousToken(token, authority, am, a);
                        return;
                    }
                }
            }, null);
    return null;
}

From source file:org.klnusbaum.udj.ArtistsLoader.java

private ArtistsResult attemptLoad(boolean attemptReauth) {
    AccountManager am = AccountManager.get(getContext());
    String authToken = "";
    try {/*from  w  ww .  j a v a 2 s  .c om*/
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (IOException e) {
        //TODO this might actually be an auth error
        return new ArtistsResult(null, ArtistsError.AUTHENTICATION_ERROR);
    } catch (AuthenticatorException e) {
        return new ArtistsResult(null, ArtistsError.AUTHENTICATION_ERROR);
    } catch (OperationCanceledException e) {
        return new ArtistsResult(null, ArtistsError.AUTHENTICATION_ERROR);
    }

    try {
        String playerId = am.getUserData(account, Constants.LAST_PLAYER_ID_DATA);
        return getArtists(playerId, authToken);
    } catch (JSONException e) {
        return new ArtistsResult(null, ArtistsError.SERVER_ERROR);
    } catch (ParseException e) {
        return new ArtistsResult(null, ArtistsError.SERVER_ERROR);
    } catch (IOException e) {
        return new ArtistsResult(null, ArtistsError.SERVER_ERROR);
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            Log.d(TAG, "soft auth failure");
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            return attemptLoad(false);
        } else {
            Log.d(TAG, "hard auth failure");
            return new ArtistsResult(null, ArtistsError.AUTHENTICATION_ERROR);
        }
    } catch (PlayerInactiveException e) {
        return new ArtistsResult(null, ArtistsError.PLAYER_INACTIVE_ERROR);
    } catch (NoLongerInPlayerException e) {
        return new ArtistsResult(null, ArtistsError.NO_LONGER_IN_PLAYER_ERROR);
    } catch (KickedException e) {
        return new ArtistsResult(null, ArtistsError.KICKED_ERROR);
    }

}