获取InputStream时,NPE用于为ClientClideSecrets传递Client_secret.json

问题描述 投票:0回答:2

我正在关注Google Calendar API的快速入门指南,但在输入流中将我的代码作为NPE。这完全是代码的副本。

InputStream in = BGTask.class.getClassLoader().getResourceAsStream("/client_secret.json");
                GoogleClientSecrets clientSecrets =
                GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

请帮助解决,我读了许多博客和问题,给出了不同的解决方案,比如把路径的完整路径,所以我尝试了你喜欢D:\ Android Development \ Mycalpp \ app \ client_Secret.json,但没有一个能够解决这个问题Android工作室。

BGTask是Class扩展到AsyncTask。这里也在示例1中示出了相同的代码。

https://www.programcreek.com/java-api-examples/index.php?api=com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets

java android
2个回答
0
投票

这是你可以做的:

选项1:

将文件(client_secret.json)放在assets /文件夹中。

然后像这样读:

    InputStream in = getAssets().open("client_secret.json");
    GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

选项2:

将文件(client_secret.json)放在res / raw文件夹中(如果没有原始文件夹创建它)。

然后像这样读:

Resources res = getResources();
InputStream in = res.openRawResource(R.raw.client_secret);
GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

希望能帮助到你!!!


-1
投票

getResourceAsStream将从您的类路径(而不是源目录)中读取文件,因此请确保client_secret.json与您的java类一起部署并且在您的类路径中

© www.soinside.com 2019 - 2024. All rights reserved.