Search code examples
javaandroidinputstreamfilenotfoundexception

Read google profile picture java.io.FileNotFoundException


I try to read the google user's profile picture after login, however, I encounter an input stream opening error. I don't want to use Glide or Picasso libraries. My code is quite standard:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            // The Task returned from this call is always completed, no need to attach
            // a listener.
            Task<GoogleSignInAccount> completedTask = GoogleSignIn.getSignedInAccountFromIntent(data);
                try {
                    final GoogleSignInAccount account = completedTask.getResult(ApiException.class);

                    String email = account.getEmail();
                    String deviceID = Settings.Secure.getString(LoginActivity.this.getContentResolver(), Settings.Secure.ANDROID_ID);
                    Uri personPhotoURL = Uri.parse(account.getPhotoUrl().toString());

                    try {
                        ContentResolver resolver = getBaseContext().getContentResolver();
                        InputStream imageStream = resolver.openInputStream(personPhotoURL);
                        Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                        String encodedImage = encodeImage(selectedImage);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

The Uri shows the right Url (it loads the picture when inserted into the browser), but imageStream opening throws "java.io.FileNotFoundException: No content provider: https://lh3.googleusercontent.com/a-/AAuE.....".

How can I solve this problem?


Solution

  • The URL is an https URL, like the one for this Web page. ContentResolver does not handle those.

    Use an image-loading library, such as Glide or Picasso, to load the image from the URL. Or, use OkHttp to perform the Web request.