0

I'm working on an app that needs to send an automatic email on button click. the problem I am currently have is that I need to read a json file and when I pass the path of the json stored in assets into into a new FileReader() I get a file not found Exception. here is how I am getting the path. (wondering if Uri.parse().toString is redundant):

private static final String CLIENT_SECRET_PATH = 
        Uri.parse("file:///android_asset/raw/sample/***.json").toString()

and here is the method I am passing it into:

sClientSecrets = GoogleClientSecrets
      .load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));

the json file that I am attemping to access is in my apps asset folder under the app root in android project directory (/app/assets/)

I am not sure what I am doing wrong here but I'm sure it is something simple. please help point me in the right direction.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Mox_z
  • 501
  • 7
  • 30
  • are you sure your **.json file is inside 'sample' folder under 'raw' inside asset directory? –  Jul 30 '17 at 06:57

4 Answers4

1

You should not access the assets using direct file path. The files are packed and the location will change on each device. You need to use a helper function to get the assets path

getAssets().open()

See this post for more information.

ApriOri
  • 2,618
  • 29
  • 48
1

You can use this function to get JSON string from assets and pass that string to the FileReader.

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("yourfilename.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
}
return json;
}
Rohit Gurjar
  • 437
  • 4
  • 12
  • I was able to use your provided method to build what I needed. Thank you. See answer I posted below. – Mox_z Jul 30 '17 at 07:19
1

Keep your file directly inside assets directory rather then raw-sample.

And then file path will be like this

private static final String CLIENT_SECRET_PATH = 
    Uri.parse("file:///android_asset/***.json").toString()

hope your problem will be solved..

0

@Rohit i was able to use the method you provided as a starting point. the only issue with it was that the gmail api that i am using requires a Reader as its parameter, not a string. here is what i did. and i am no longer getting filenotfoundexception. thank you very much.

public InputStreamReader getJsonStreamReader(String file){
    InputStreamReader reader = null;
    try {
        InputStream in = getAssets().open(file);
        reader = new InputStreamReader(in);
    }catch(IOException ioe){
        Log.e("launch", "error : " + ioe);
        }
    return reader;
}
Mox_z
  • 501
  • 7
  • 30