In Android Studio, I'm trying to send a request to a Google spreadsheet. To do this, I use sample code from Java Quickstart in the official Google Sheets API documentation. But there is a problem - the code cannot find the credentials.json file.

There is a way:

private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; 

And there are two ways to get this file, both of which do not find anything and as a result, in in it turns out to be NULL:

 InputStream in = new FileInputStream(CREDENTIALS_FILE_PATH); //InputStream in = GoogleSheets.class.getResourceAsStream(CREDENTIALS_FILE_PATH); 

Tell me, please, how to solve this problem?

enter image description here

  • if all the same how - put in a package with a class and it will be found by the code that you gave in the question - Stranger in the Q
  • @StrangerintheQ the fact of the matter is that there is no one. In the case of getResouceAsStream there will be a NullPointerException, and when FileInputStream, the error FileNotFoundException comes out: /credentials.json (No such file or directory) - Mikhail Ershov

1 answer 1

In the case of an android, you can put the file in the assets folder and get an InputStream from it like this:

 public static final String CREDENTIALS_FILE_PATH = "/credentials.json"; public static InputStream getInputStreamFromAssets(Context context, String fileName) { return new InputStreamReader(context.getAssets().open(fileName), "UTF-8"); } 

Further somewhere in the code where there is a context:

 InputStream in = getInputStreamFromAssets(context, CREDENTIALS_FILE_PATH ); 

If the assets folder is not in the project, you need to create it manually. To do this, simply create a folder named assets in src/main

  • And how can I get context if the method in which I want to get an InputStream is a static method? I can not use this, it turns out, and what other options? - Mikhail Ershov
  • @ MihailERShov, pass the context to the method through the arguments thereof. Or make a singleton for the application context (do not activate, otherwise there will be a memory leak). It is better to pass through the parameter. - YurySPb