首页 > 解决方案 > Why is GoogleCredentials.fromStream(myJson) coming out null?

问题描述

I have a service account for which I downloaded a Json file to my android studio's 'assets' folder. I then copy/pasted code from google's own documentation and am getting null.

I have tried various ways to read my json file, but all are null.

void AuthExplicit(){

        GoogleCredentials credentials = null;
        try {
               credentials = GoogleCredentials.fromStream(new FileInputStream("auth.json"))
                    .createScoped(Lists.newArrayList(Collections.singleton("https://www.googleapis.com/auth/cloud-platform")));
        } 
        catch (IOException e) {
            e.printStackTrace();
        }

        new RefreshCred().execute(credentials);
        token = credentials.getAccessToken();
        tokenString = token.toString();

    }

EDIT1 So I have created a raw folder under res and put my auth.json file in there. Then changed my code to the below. credentials is still null.

void AuthExplicit(){
        try
        {
            InputStream stream = getResources().openRawResource(R.raw.auth);
            GoogleCredentials credentials = GoogleCredentials.fromStream(stream);
            token = credentials.getAccessToken();
            tokenString = token.toString();
            Log.i("Token",tokenString);
            new RefreshCred().execute(credentials);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

    }

标签: javaandroidgoogle-cloud-platformgoogle-api

解决方案


您应该将资产提取到手机上的某个目录,而不是直接从资产文件夹中加载。有关更多详细信息,请查看答案。


推荐阅读